AngularJS Menu and Submenu by JSON with Twitter Bootstrap

angularjs, javascript, json

Solution

Change the sub menu data populate template to

<li ng-repeat="subItem in link.sub">
    <a href="{{subItem.url}}">{{subItem.name}}</a>
</li>

`link.sub` is the sub collection of the current data object, and then loop through each item of the sub collections.

Demo on jsFiddle

Problem

I am new to AngularJS. I am working on a personal project using Twitter Bootstrap so I can learn AngularJS. I have my data in a JSON file. The project-title and main menu links are being populated just fine. There is a submenu under one of those links and that's what I cannot get to populate. What I would like to do is to load the submenu using an ng-repeat. So basically I'm dealing with an ng-repeat inside of an ng-repeat. Any and all tips welcomed. Thanks! My controller looks like this: ``` 'use strict'; var app = angular.module('myApp', []); app.controller('NavCtrl', function($scope, $http) { $http.get('app/content/nav.json').success(function(data) { $scope.nav = data; $scope.links = data.links; }); }); ``` My JSON: ``` { "projectTitle" : "My Website Title", "links" : [ {"name" : "Home", "url" : "/", "className" : ""}, {"name" : "About", "url" : "/about", "className" : ""}, {"name" : "Contact", "url" : "/contact", "className" : ""}, {"name" : "Categories", "url" : "/categories", "className" : "dropdown", "sub" : [ {"name" : "Tech Stuff", "url" : "/techStuff"}, {"name" : "AngularJS", "url" : "/angularJS"}, {"name" : "HTML5", "url" : "/html5"}, {"name" : "Javascript", "url" : "/javascript"}, {"name" : "jQuery", "url" : "/jquery"} ] } ] } ``` My HTML: ``` <div ng-controller="NavCtrl" class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="brand" href="#">{{nav.projectTitle}}</a> <div class="nav-collapse collapse"> <ul class="nav"> <li ng-repeat="link in links" class="{{link.className}}"> <a href="{{link.url}}" class="{{link.sub && 'dropdown-toggle' || ''}}" data-toggle="{{link.sub && 'dropdown' || ''}}">{{link.name}} <b ng-show="link.sub" class="caret"></b> </a> <ul class="dropdown-menu" ng-show="link.sub"> <li ng-repeat="sub in links"> <a href="">{{sub.name}}</a> </li> </ul> </li> </ul> </div> </div> </div> </div> ```

Original source