[英]Angular JS dynamic directive template
我最近在尝试在angular js中创建递归树视图时遇到了以下代码:
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'}
];
这段代码运行良好,但是collection指令和member指令的模板是硬编码的。 我想知道是否有办法从html获取集合和成员的模板。 像这样:
<div ng-controller="TestCtrl">
<ul recurse="testList">
<li>{{member.text}}</li>
</ul>
</div>
recurse伪指令将代替collection伪指令,但递归的模板将是其附加到的<ul>
元素。
同样,成员指令的模板将从<ul>
元素的子代创建; 在这种情况下, <li>
元素。
这可能吗?
提前致谢。
在指令中,您可以使用transclude: 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>'
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.