我正在尝试使用angularjs创建嵌套指令。
这是我的代码:(http://jsfiddle.net/TH55L/)
JS:
myApp.directive('nodo', function ($compile) {
return {
restrict: 'E',
terminal: true,
scope: {
n: "="
},
link: function (scope, element, attrs) {
var template = "<p>{{n.name}}</p>";
if (scope.n.nodo != null) {
template += '<nodo n="n.nodo"></nodo>';
}
var newElement = angular.element(template);
$compile(newElement)(scope);
element.replaceWith(newElement);
}
}
})
function MyCtrl($scope) {
$scope.nodo = {
"name": "Level 0",
"nodo": {
"name": "Level 1",
"nodo": {
"name": "Level 2",
"nodo": {
"name": "Level 3",
"nodo": null
}
}
}
};
}
HTML:
<div ng-controller="MyCtrl">
<nodo n="nodo"></nodo>
</div>
预期结果如下:
<p>Level 0</p><p>Level 1</p><p>Level 2</p><p>Level 3</p>
但我只是得到了这个:
<p>Level 0</p>
就像$ compile(newElement)(范围)不能识别指令一样。
以下是Knockoutjs中我想做的一个例子:http://jsfiddle.net/y64rY/
答案 0 :(得分:1)
为了让它们像您想要的那样重复,您应该将动态对象转换为数组,然后使用data-ng-repeat指令:
scope.nodes = [];
function recursive(parent){
scope.nodes.push({
name: parent.name
});
if(parent.nodo){
recursive(parent.nodo);
}
}
recursive(scope.nodo);
template: '<div><p data-ng-repeat="node in nodes">{{ node.name }}</p></div>',
jsfiddle http://jsfiddle.net/kEyqz/
答案 1 :(得分:0)
您可以使用两个指令完成此操作:
var myApp = angular.module('myApp',[]);
myApp.directive('tree', function ($compile) {
return {
restrict: 'E',
terminal: true,
replace: true,
scope: {
root: "="
},
link: function (scope, element, attrs) {
var nodoTemplate = '<nodo node="node"></nodo>';
/* Your first nodo is the root. We put it on scope to use this on $compile */
scope.node = scope.root
while (scope.node != null) {
/* Compile and append the nodo */
var c = $compile(nodoTemplate)(scope);
element.append(c);
/* go to next nodo */
scope.node = scope.node.nodo;
}
}
}
});
myApp.directive('nodo', function ($compile) {
return {
restrict: 'E',
replace: true,
scope: {
node: "="
},
template: "<p></p>",
link: function(scope, element, attrs) {
element.text(scope.node.name);
}
}
})
在你的HTML中:
<tree root="nodo"></tree>