角JS动态指令模板 [英] Angular JS dynamic directive template
问题描述
我最近碰到这个code试图创建角的js递归树视图时就来了:
I recently came across this code when trying to create a recursive tree view in 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中:
The directive is used in the HTML like so:
<div ng-controller="TestCtrl">
<collection collection="testList"></collection>
</div>
在哪里testList是TestCtrl JSON对象的数组,例如:
Where testList is an array of JSON objects in TestCtrl, for example:
$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'}
];
这code效果很好,但对收集指令和成员指令的模板是硬codeD。我不知道是否有一种方式来获得收集和成员从HTML模板。事情是这样的:
This code works well, but the templates for the collection directive and the member directive are hard coded. I was wondering if there is a way to get the templates for collection and member from the html. Something like this:
<div ng-controller="TestCtrl">
<ul recurse="testList">
<li>{{member.text}}</li>
</ul>
</div>
递归指令将是集合指令的替代,但对递归的模板将在该&LT; UL&GT;
元素,它是连接到
同样,成员指令的模板,将会从孩子们创造了&LT; UL&GT;
元素;在&LT;李方式&gt;
在这种情况下,元素
Likewise, the member directive's template would be created from the children of the <ul>
element; the <li>
element in this case.
这可能吗?
先谢谢了。
推荐答案
在你的指令,你可以使用 transclude:真正的
和HTML定义模板的一部分。该指令模板可以包括使用它 NG-transclude
。
In your directive you can use transclude: true
and define parts of your template in HTML. The directive template can include it using ng-transclude
.
想象一下这个模板:
<div my-list="testList">
<b>{{item.text}}</b>
</div>
在你的指令,你可以使用transclusion控制列表项被呈现方式:
In your directive you can use transclusion to control how your list items gets rendered:
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>'
};
});
这篇关于角JS动态指令模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!