ilyo
ilyo

Reputation: 36411

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

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>

Upvotes: 6

Views: 9707

Answers (1)

Piran
Piran

Reputation: 7328

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.

Upvotes: 7

Related Questions