Create tiered lists with ng-repeat

I am trying to make a multi-level list from an object that contains 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 only display the first 2 levels of the menu and ignore 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> 
+6
source share
1 answer

You see only two levels because you have only two levels of loops: ng-repeat simply repeats what it gave, and does not call itself recursively.

Your first cycle is repeated only at the first level, and the second cycle is repeated at the second level. There is nothing in the code that would look for 3rd level or deeper levels.

You can call the same ng-include recursively, and that works. I demonstrated this in plunker here: http://plnkr.co/edit/NBDgqKOy2qVMQeykQqTY?p=preview

But this code is pretty terrible, using ng-init to copy the values. It works, but it is probably better to write as a directive.

+7
source

All Articles