[英]How do I recursively iterate over an object that has unknown hierarchies with Angular JS?
So take this example: 举个例子:
http://jsfiddle.net/7U5Pt/ http://jsfiddle.net/7U5Pt/
Here I've got an object that describes a (very basic) menu. 在这里,我有一个描述(非常基本的)菜单的对象。 Each item can have multiple children with potentially unlimited levels of hierarchy.
每个项目可以有多个子级,这些子级可能具有无限的层次结构。 The
ng-repeat
directives I'm using to turn it into <ul><li>
elements work fine for the first two levels, but not for the third or any subsequent level of the hierarchy. 我用来将其转换为
<ul><li>
元素的ng-repeat
指令在层次结构的前两个级别上工作正常,但在层次结构的第三个级别或任何后续级别上则无法正常工作。
What's the best way to recursively iterate over this object, dealing with unlimited levels of children? 递归地迭代此对象并处理无限级别的子级的最佳方法是什么?
Any help much appreciated! 任何帮助,不胜感激!
Here's the code incase the fiddle goes away: 这是小提琴消失的代码:
HTML: HTML:
<div ng-app="myApp">
<div ng-controller="myCtrl">
<nav class="nav-left">
<ul ng-repeat="item in mytree.items">
<li>NAME: {{ item.name }}
<ul ng-repeat="item in item.children.items">
<li>SUB NAME: {{ item.name }}</li>
</ul>
</li>
</ul>
</nav>
</div>
JS: JS:
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function ($scope) {
$scope.mytree = {
"items": [{
"name": "one",
"children": {
"items": [
{
"name": "one sub a",
"children": {
"items": [{
"name": "one sub level two a"
},
{
"name": "one sub level two b"
}]
}
},
{
"name": "one sub b"
}
]
}
},
{
"name": "two"
},
{
"name": "three"
},
{
"name": "four",
"children": {
"items": [{
"name": "four sub a"
},
{
"name": "four sub b"
}]
}
},
{
"name": "five"
}]
};
});
So it turns out that the best way to do this, for anyone interested, is with the angular-recursion
helper here: 因此,事实证明,对于任何感兴趣的人,最好的方法是在这里使用
angular-recursion
帮助器:
https://github.com/marklagendijk/angular-recursion https://github.com/marklagendijk/angular-recursion
This allows you to call the ng-repeat function recursively. 这使您可以递归调用ng-repeat函数。 So in your view, something like:
因此,您认为类似:
<tree family="mytree"></tree>
and then define a directive for that calls itself like so: 然后为该调用定义一个指令,如下所示:
.directive('tree', function(RecursionHelper) {
return {
restrict: "E",
scope: {family: '='},
template:
'{{ family.name }}'+
'<ul ng-if="family.children">' +
'<li ng-repeat="child in family.children">' +
'<tree family="child"></tree>' +
'</li>' +
'</ul>',
compile: function(element) {
return RecursionHelper.compile(element);
}
};
});
Apparently the recursion helper is necessary to stop some sort of infinite loop thing, as discussed here . 显然,递归助手是需要停止某种无限循环的事情,如讨论在这里 。 Thanks to @arturgrzesiak for the link!
感谢@arturgrzesiak提供的链接!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.