Recursion with ng-repeat in Angular

13,962

Solution 1

You can simply use ng-include to make a partial and call it recursively: Partial should be something like this:

<ul>
    <li ng-repeat="item in item.subItems">
      <a href="{{item.href}}" ng-class="{'nav-link nav-toggle': item.subItems && item.subItems.length > 0}">
          <span class="title">{{item.text}}</span>
      </a>
      <div ng-switch on="item.subItems.length > 0">
        <div ng-switch-when="true">
          <div ng-init="subItems = item.subItems;" ng-include="'partialSubItems.html'"></div>  
        </div>
      </div>
    </li>
</ul>

And your html:

<ul class="page-sidebar-menu" data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200" ng-class="{'page-sidebar-menu-closed': settings.layout.pageSidebarClosed}">
    <li ng-repeat="item in menuItems" ng-class="{'start': item.isStart, 'nav-item': item.isNavItem}">
        <a href="{{item.href}}" ng-class="{'nav-link nav-toggle': item.subItems && item.subItems.length > 0}">
            <span class="title">{{item.text}}</span>
        </a>
        <ul ng-if="item.subItems && item.subItems.length > 0" class="sub-menu">

            <li ng-repeat="item in item.subItems" ng-class="{'start': item.isStart, 'nav-item': item.isNavItem}">
                 <a href="{{item.href}}" ng-class="{'nav-link nav-toggle': item.subItems && item.subItems.length > 0}">
                    <span class="title">{{item.text}}</span>
                </a>

                 <div ng-switch on="item.subItems.length > 0">
                    <div ng-switch-when="true">
                      <div ng-init="subItems = item.subItems;" ng-include="'newpartial.html'"></div>  
                    </div>
                </div>

            </li>
        </ul>
    </li>
</ul>

Here is the working plunker http://plnkr.co/edit/9HJZzV4cgacK92xxQOr0?p=preview

Solution 2

You can achieve this simply by including a javascript template and template include using ng-include

define javascript template

<script type="text/ng-template" id="menu.html">...</script>

and include it like:

<div ng-if="item.subItems.length" ng-include="'menu.html'"></div>

Example: In this example I used basic html without any class you can use classes as you need. I just shown basic recursion structure.

In html:

<ul>
    <li ng-repeat="item in menuItems">
      <a href="{{item.href}}">
        <span>{{item.text}}</span>
      </a>
      <div ng-if="item.subItems.length" ng-include="'menu.html'"></div>
    </li>
</ul>


<script type="text/ng-template" id="menu.html">
   <ul>
      <li ng-repeat="item in item.subItems">
        <a href="{{item.href}}">
          <span>{{item.text}}</span>
        </a>
        <div ng-if="item.subItems.length" ng-include="'menu.html'"></div>
      </li>
   </ul>
</script>

PLUNKER DEMO

Solution 3

If your intention is to draw an menu with indefinite level of sub items, probably a good implementation is to make a directive.

With a directive you will be able to assume more control over your menu.

I created a basic exepmle with full recursion, on with you can see an easy implementation of more than one menu on the same page and more than 3 levels on one of the menus, see this plunker.

Code:

.directive('myMenu', ['$parse', function($parse) {
    return {
      restrict: 'A',
      scope: true,
      template:
        '<li ng-repeat="item in List" ' +
        'ng-class="{\'start\': item.isStart, \'nav-item\': item.isNavItem}">' +
        '<a href="{{item.href}}" ng-class="{\'nav-link nav-toggle\': item.subItems && item.subItems.length > 0}">'+
        '<span class="title"> {{item.text}}</span> ' +
        '</a>'+
        '<ul my-menu="item.subItems" class="sub-menu"> </ul>' +
        '</li>',
      link: function(scope,element,attrs){
        //this List will be scope invariant so if you do multiple directive 
        //menus all of them wil now what list to use
        scope.List = $parse(attrs.myMenu)(scope);
      }
    }
}])

Markup:

<ul class="page-sidebar-menu" 
    data-keep-expanded="false" 
    data-auto-scroll="true" 
    data-slide-speed="200" 
    ng-class="{'page-sidebar-menu-closed': settings.layout.pageSidebarClosed}"
    my-menu="menuItems">
</ul>

Edit

Some notes

When it comes to make the decision about ng-include(that i think is a fair enough solution) or .directive, you have to ask yourself at least two questions first. Does my code fragment going to need some logic? If not you could as well just go for the ng-include. But if you are going to put more logic in the fragment making it customizable, make changes to the element or attrs (DOM) manipulation, you should go for directive. As well one point that make me fell more confortable with the directive is reusability of the code you write, since in my example you can give controll more and make a more generic one i assume you should go for that if your project is big and needs to grow. So the second question does my code going to be reusable?

A reminder for a clean directive is that instead of template you could use the templateUrl, and you can give a file to feed the html code that is currently in the template.

If you are using 1.5+ you can now choose to use .component. Component is a wrapper arroud .direcitve that has a lot less boilerplate code. Here you can see the diference.

                  Directive                Component

bindings          No                       Yes (binds to controller)
bindToController  Yes (default: false)     No (use bindings instead)
compile function  Yes                      No
controller        Yes                      Yes (default function() {})
controllerAs      Yes (default: false)     Yes (default: $ctrl)
link functions    Yes                      No
multiElement      Yes                      No
priority          Yes                      No
require           Yes                      Yes
restrict          Yes                      No (restricted to elements only)
scope             Yes (default: false)     No (scope is always isolate)
template          Yes                      Yes, injectable
templateNamespace Yes                      No
templateUrl       Yes                      Yes, injectable
terminal          Yes                      No
transclude        Yes (default: false)     Yes (default: false)

Source angular guide for component

Edit

As sugested by Mathew Berg if you want not to include the ul element if the list of subItems is empty you can change the ul to this something like this <ul ng-if="item.subItems.length>0" my-menu="item.subItems" class="sub-menu"> </ul>

Solution 4

After reviewing these options I found this article very clean/helpful for an ng-include approach that handles model changes well: http://benfoster.io/blog/angularjs-recursive-templates

In summary:

<script type="text/ng-template" id="categoryTree">
    {{ category.title }}
    <ul ng-if="category.categories">
        <li ng-repeat="category in category.categories" ng-include="'categoryTree'">           
        </li>
    </ul>
</script>

then

<ul>
    <li ng-repeat="category in categories" ng-include="'categoryTree'"></li>
</ul>  

Solution 5

In order to make recursion in Angular, I would love to use the basic feature of angularJS and i.e directive.

index.html

<rec-menu menu-items="menuItems"></rec-menu>

recMenu.html

<ul>
  <li ng-repeat="item in $ctrl.menuItems">
    <a ng-href="{{item.href}}">
      <span ng-bind="item.text"></span>
    </a>
    <div ng-if="item.menuItems && item.menuItems.length">
      <rec-menu menu-items="item.menuItems"></rec-menu>
    </div>
  </li>
</ul>

recMenu.html

angular.module('myApp').component('recMenu', {
  templateUrl: 'recMenu.html',
  bindings: {
    menuItems: '<'
  }
});

Here is working Plunker

Share:
13,962
ProfK
Author by

ProfK

I am a software developer in Johannesburg, South Africa. I specialise in C# and ASP.NET, with SQL Server. I have, in some way or another, been involved in software development for about eighteen years, but always learning something new. At the moment that is WPF and MVVM.

Updated on June 06, 2022

Comments

  • ProfK
    ProfK almost 2 years

    I have the following data structure for items in my sidemenu, in an Angular app based on a paid-for web site theme. The data structure is my own, and the menu is derived from the original menu view with all items in the ul hard coded.

    In SidebarController.js:

    $scope.menuItems = [
        {
            "isNavItem": true,
            "href": "#/dashboard.html",
            "text": "Dashboard"
        },
        {
            "isNavItem": true,
            "href": "javascript:;",
            "text": "AngularJS Features",
            "subItems": [
                {
                    "href": "#/ui_bootstrap.html",
                    "text": " UI Bootstrap"
                },
                ...
            ]
        },
        {
            "isNavItem": true,
            "href": "javascript:;",
            "text": "jQuery Plugins",
            "subItems": [
                {
                    "href": "#/form-tools",
                    "text": " Form Tools"
                },
                {
                    "isNavItem": true,
                    "href": "javascript:;",
                    "text": " Datatables",
                    "subItems": [
                        {
                            "href": "#/datatables/managed.html",
                            "text": " Managed Datatables"
                        },
                        ...
                    ]
                }
            ]
        }
    ];
    

    Then I have the following partial view bound to that model as follows:

    <ul class="page-sidebar-menu" data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200" ng-class="{'page-sidebar-menu-closed': settings.layout.pageSidebarClosed}">
        <li ng-repeat="item in menuItems" ng-class="{'start': item.isStart, 'nav-item': item.isNavItem}">
            <a href="{{item.href}}" ng-class="{'nav-link nav-toggle': item.subItems && item.subItems.length > 0}">
                <span class="title">{{item.text}}</span>
            </a>
            <ul ng-if="item.subItems && item.subItems.length > 0" class="sub-menu">
                <li ng-repeat="item in item.subItems" ng-class="{'start': item.isStart, 'nav-item': item.isNavItem}">
                    <a href="{{item.href}}" ng-class="{'nav-link nav-toggle': item.subItems && item.subItems.length > 0}">
                        <span class="title">{{item.text}}</span>
                    </a>
                </li>
            </ul>
        </li>
    </ul>
    

    NOTE There may be $scope properties in the view bindings you don't see in the model, or vice versa, but that is because I have edited them for brevity. Now because the second level li doesn't also contain a conditional ul for its own subItems, the sub-items under the Datatable menu item don't get rendered.

    How can I create a view or template, or both, that will bind recursively to the model, so that all sub-items of all sub-items are rendered? This will normally only be up to four levels.