Creating multi-level lists with ng-repeat

Deadly 提交于 2020-01-01 10:08:49

问题


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: '#',
        }
    ];
}

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>

回答1:


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.

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.

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

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.



来源:https://stackoverflow.com/questions/14812909/creating-multi-level-lists-with-ng-repeat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!