我在使用Angular的嵌套列表指令时遇到问题。每当我尝试运行我的代码时,浏览器会在递归调用指令时崩溃。
如果数据中的children
属性中包含项目,我想输出新的列表项。
这是我的代码的小提琴,我删除了指令调用自身,以便它不会崩溃浏览器。 http://jsfiddle.net/8p3bf4ec/
JS:
var jsonData = {
"title": "Home",
"author": "Mary",
"children": [
{
"title": "Clothing",
"author": "Robert",
"children": [
{
"title": "Shirts",
"author": "Bill",
"children": []
}
]
},
{
"name": "Electronics",
"author": "William",
"children": []
}
]
};
angular.module('myApp', []);
angular.module('myApp').directive('itemList', function() {
return {
scope: true,
templateUrl: 'itemListTemplate.html',
controller: function($scope) {
$scope.nodes = jsonData;
console.log($scope.nodes);
}
};
});
模板:
<div ng-app="myApp">
<item-list></item-list>
<script type="text/ng-template" id="itemListTemplate.html">
<ul>
<li ng-repeat="node in nodes">
{{node.title}}
</li>
</ul>
<!-- Removed this because it makes the browser crash
<item-list></item-list>
-->
</script>
</div>
答案 0 :(得分:1)
这是因为你无限遍历jsonData而不是每个节点的子节点。我想你根本不应该使用指令,因为没有太多的逻辑,它增加了不必要的复杂性。只需使用ng-include而不是指令。像这样:
<script type="text/ng-template" id="tree-view">
<ul>
<li ng-repeat="item in items">
<!-- any data you want to display from item itself -->
<div
ng-if="item.children && item.children.length"
ng-init="items=item.children"
ng-include="'tree-view'">
</div>
</li>
</ul>
</script>
<div class="tree-view" ng-include="'tree-view'"></div>