使用 ng-repeat 创建多级列表 [英] Creating multi-level lists with ng-repeat
问题描述
我正在尝试从包含嵌套数据的对象创建一个多级列表:
I am trying to make a multi-level list from an object that contains the nesting data:
function linksRarrange($scope) {
$scope.links = [
{
text: 'Menu Item 1',
url: '#',
},{
text: 'Menu Item 2',
url: '#',
submenu: [
{
text: 'Sub-menu Item 3',
url: '#',
},{
text: 'Sub-menu Item 4',
url: '#',
submenu: [
{
text: 'Sub-sub-menu Item 5',
url: '#',
},{
text: 'Sub-sub-menu Item 6',
url: '#',
}
]
}
]
},{
text: 'Menu Item 3',
url: '#',
}
];
}
为什么只输出前2级菜单而忽略第三级?
Why does this outputs only the first 2 level menus and ignores the third?
<ul>
<li ng-repeat="link in links"><a href="{{link.url}}">{{link.text}}</a>
<ul>
<li ng-repeat='sublink in link.submenu'><a href="{{sublink.url}}">{{sublink.text}}</a></li>
</ul>
</li>
</ul>
推荐答案
你只看到两个级别,因为你只有两个级别的循环:ng-repeat 只是重复它给定的内容,并没有调用自身递归.
You're only seeing two levels because you've only got two levels of loops: the ng-repeat just repeats over what it's given, and does not call itself recursively.
您的第一个循环只是在第一级重复,而您的第二个循环只是在第二级重复.您的代码中没有任何内容要寻找第 3 级或更深的层次.
Your first loop just repeats over the first level, and your second loop just repeats over the second level. There's nothing in your code looking for a 3rd level or any deeper levels.
您可以递归调用相同的 ng-include,这似乎有效.我已经在 plunker 中演示了这个:http://plnkr.co/edit/NBDgqKOy2qVMQeykQqTY?p=preview一个>
You can call the same ng-include recursively, and that appears to work. I've demo'ed this in plunker here: http://plnkr.co/edit/NBDgqKOy2qVMQeykQqTY?p=preview
但是使用 ng-init 复制值的代码非常可怕.它有效,但它可能更好地编写为指令.
But that code is pretty dreadful using ng-init to copy the values around. It works, but it could probably be better written as a directive.
这篇关于使用 ng-repeat 创建多级列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!