javascript之Angular JS 动态指令模板

wuhuacong 阅读:82 2026-05-17 15:37:00 评论:0

我最近在尝试在 Angular js 中创建递归 TreeView 时遇到了这段代码:

testApp.directive('collection', function () { 
    return { 
        restrict: 'E', 
        replace: true, 
        scope: {collection: '='}, 
        template: '<ul><member x-ng-repeat="member in collection" x-member="member"></member></ul>' 
    }; 
}); 
 
testApp.directive('member', function ($compile) { 
    return { 
        restrict: 'E', 
        replace: true, 
        scope: {member: '='}, 
        template: '<li>{{member.title}}</li>', 
        link: function (scope, element, attrs) { 
            if (angular.isArray(scope.member.children)) { 
                $compile('<collection x-collection="member.children"></collection>')(scope, function (cloned, scope) { 
                    element.append(cloned); 
                }); 
            } 
        } 
    }; 
}); 

该指令在 HTML 中的使用如下:

<div ng-controller="TestCtrl"> 
    <collection collection="testList"></collection> 
</div> 

其中testList是TestCtrl中的JSON对象数组,例如:

$scope.testList = [ 
    {text: 'list item 1'}, 
    {text: 'list item 2', children: [ 
        {text: 'sub list item 1'}, 
        {text: 'sub list item 2'} 
    ]}, 
    {text: 'list item 3'} 
]; 

此代码运行良好,但集合指令和成员指令的模板是硬编码的。我想知道是否有办法从 html 中获取集合和成员的模板。像这样的事情:

<div ng-controller="TestCtrl"> 
    <ul recurse="testList"> 
        <li>{{member.text}}</li> 
    </ul> 
</div> 

递归指令将替代集合指令,但递归模板将是 <ul>它附加到的元素。

同样,成员指令的模板将从 <ul> 的子级创建。元素; <li>本例中的元素。

这可能吗?

提前致谢。

请您参考如下方法:

在指令中,您可以使用 transinclude: true 并在 HTML 中定义模板的部分内容。指令模板可以使用 ng-transclude 包含它。

想象一下这个模板:

<div my-list="testList"> 
  <b>{{item.text}}</b> 
</div> 

在指令中,您可以使用嵌入来控制列表项的渲染方式:

module.directive('myList', function () { 
    return { 
        restrict: 'A', 
        transclude: true, 
        replace: true, 
        scope: { 
          collection: '=myList' 
        }, 
        template: '<ul><li ng-repeat="item in collection"><div ng-transclude></div><ul><li ng-repeat="item in item.children"><div ng-transclude></li></ul></li></ul>' 
    }; 
}); 

Plunker


标签:JavaScript
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号