Alex Muro
Alex Muro

Reputation: 125

Nested ng-repeat on data of uneven depth

In angular js I am trying to build my site navigation via a controller. In the navigation menu, some menus have submenus and some don't. Here is a simplified version of my nav controller.

function NavCtrl($scope) {
  $scope.menus = [
    {"name": "Destinations",
     "url": "/#/destinations",
    "submenu":[
    {
      "name":"America",
      "url":"#"
    },
    {
      "name":"Europe",
      "url":"#"
    }
    ]},
    {"name": "Friend Finder",
     "url": "/#/friend-finder"},
    {"name": "Blog",
     "url": "/#/blog"},
  ];
}

and here is the code I use to output it:

<ul class="nav" ng-controller="NavCtrl">
      <li ng-repeat="menu in menus">
        <a href="{{menu.url}}">
          {{menu.name}}
        </a>
        <ul>
          <li ng-repeat="submenu in menu.submenu">
            <a href="{{submenu.url}}">
            {{submenu.name}}
            </a>
          </li>
        </ul>
      </li>
    </ul>

Is there someway for me to not output the inner ul if a menu does not have a submenu?

Upvotes: 0

Views: 1025

Answers (1)

slacktracer
slacktracer

Reputation: 6306

I haven't tested it but, I believe you can just not show your ul if there is no menu.submenu (that's what you want right?) by adding something like data-ng-show="menu.submenu" to your inner ul.

Like this:

<ul class="nav" ng-controller="NavCtrl">
  <li ng-repeat="menu in menus">
    <a href="{{menu.url}}">
      {{menu.name}}
    </a>
    <ul data-ng-show="menu.submenu">
      <li ng-repeat="submenu in menu.submenu">
        <a href="{{submenu.url}}">
        {{submenu.name}}
        </a>
      </li>
    </ul>
  </li>
</ul>

Perhaps you'll need a better test, or set submenu to false, as I'm not sure an empty array or object will behave as I'm expecting, but I'm pretty sure that's the general idea.

Upvotes: 3

Related Questions