Search code examples
angularjsangularjs-routing

How to dynamically build a menu from json?


Right now my main menu html is being edited by hand. But i want to create the main menu dynamically from json. how can this be done?

I have the following app.js:

var app = angular.module('MyApp', ['ngRoute', 'oc.lazyLoad']);
app.config(function($routeProvider, $locationProvider){
    var routeDef = function (name) {
            return {
                    templateUrl: 'partials/' + name + '.htm',
                    controller: name.charAt(0).toUpperCase() + name.slice(1) + 'Ctrl',
                    resolve: {
                            loader: ['$ocLazyLoad', function($ocLazyLoad) {
                                    return $ocLazyLoad.load('controllers/' + name + '.js');
                            }]
                    }
            };
    };
    $routeProvider.
            when('/home', routeDef('home')).
            when('/controller1', routeDef('controller1')).
            when('/controller2', routeDef('controller2')).
            otherwise({ redirectTo: '/home' });
    // $locationProvider.html5Mode(true);
});

app.controller('NavCtrl', ['$scope', '$location', function ($scope, $location) {
  $scope.navClass = function (page) {
    var currentRoute = $location.path().substring(1) || 'index';
    return page === currentRoute ? 'active' : '';
  };
}]);

for the html:

<html>
...
<body ng-controller="MyApp">
...
  <ul class="nav nav-pills" ng-controller="NavCtrl">
    <li role="presentation" ng-class="navClass('home')"><a href="#/home">Home</a></li>
    <li role="presentation" ng-class="navClass('controller1')"><a href="#/controller1">Controller1</a></li>
    <li role="presentation" ng-class="navClass('controller2')"><a href="#/controller2">Controller2</a></li>
  </ul>

...
    <div ng-view></div>
...
</body>
</html>

Solution

  • Yes, here is it:

    function SidebarLoader($http) {
        this.getMenu = getMenu;
    
        ////////////////
    
        function getMenu(onReady, onError) {
          var menuJson = '/app/json/sidebar.menu.json',
              menuURL  = menuJson + '?v=' + (new Date().getTime()); // jumps cache
    
          onError = onError || function() { alert('Failure loading menu'); };
    
          $http
            .get(menuURL)
            .success(onReady)
            .error(onError);
        }
    }
    

    controller :

       SidebarLoader.getMenu(sidebarReady);
    
          function sidebarReady(items) {
            $scope.menuItems = items;
          }
    

    jade/html:

    li(ng-repeat='item in menuItems | limitTo: 3 ', ng-class="{'dropdown': item.submenu}", dropdown="!!item.submenu")