如何从json动态构建菜单?

时间:2015-11-04 09:41:01

标签: angularjs angularjs-routing

现在我的主菜单html正在手工编辑。但我想从json动态创建主菜单。怎么办呢?

我有以下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' : '';
  };
}]);

表示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>

1 个答案:

答案 0 :(得分:1)

是的,就是这样:

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);
    }
}

控制器:

   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")