Andres Gonzalez Andres Gonzalez - 1 month ago 6
AngularJS Question

how to get conditional submenus using ng-repeat and ui-router in angular?

I am trying to build a menu where only some of the menu items would have submenus. I am using ng-repeat and ui-router. For example, these are a reduced set of main menu items:

vm.routes = [
{ name: 'Home', path: 'home' },
{ name: 'Streams', path: 'streams' },
{ name: 'Overlays', path: 'overlays' },
{ name: 'Admin', path: 'admin' }
];


In the HTML I am using this:

<li class="vic-menu-item"
ng-repeat="route in vm.routes"
<a ui-sref="{{route.path}}">{{route.name}}</a>
</li>


Now I want to add sub-menus to the Admin menu. But other menu items may not have submenus, like Home for example. So its inclusion would have to be conditional on some property in my vm.routes array.

Question: using the Angular way, how do I use conditionals in the ng-repeat so I can build the menu ul tag with optional sub menu items?

I have looked at some of the similar questions but they are confusing to me and none appear to answer this specific technique.

Thanks,
-Andres

Answer

First of all you should create array with same structure

vm.routes = [
        { name: 'Home', path: 'home', submenu:[
         {name: 'Submenu-1', path: ''},
         {name: 'Submenu-2', path: ''}
        ] },
        { name: 'Streams', path: 'streams' },
        { name: 'Overlays', path: 'overlays' },
        { name: 'Admin', path: 'admin' }
    ];

After that in html:

<li class="vic-menu-item" 
    ng-repeat="route in vm.routes" 
    <a ui-sref="{{route.path}}">{{route.name}}</a>
    <ul ng-if='route.submenu'>
      <li ng-repeat='submenu in route.submenu'>
         <a ui-sref="{{submenu.path}}">{{submenu.name}}</a>
      </li>
    </ul>
</li>