如何在AngularJS中将配置从一个模块推送到另一个模块

时间:2015-04-27 08:49:40

标签: angularjs configuration

我正在寻找一种方法,将一些配置从一些模块“发送”或“注册”到一个模块。

这个想法是不同的模块将拥有自己的路由配置。一个模块控制器将根据这些配置构建菜单。

我想“发送”或“注册”配置而不是查询,因为菜单控制器无法知道哪些模块可用。

1 个答案:

答案 0 :(得分:0)

以下是我需要的解决方案:

每个模块使用$ routeProvider定义自己的路由,其中​​自定义参数定义路径是否应显示在菜单中,另一个自定义参数是否显示名称。 (参见上面的模块A示例)。

然后菜单控制器将循环$ route.routes变量(包含所有已定义的路径)来构建菜单。 (参见上面的模块B示例)。

模块A:

angular
  .module('module-a', ['ngRoute'])

  .config(function ($routeProvider) {
    $routeProvider
      .when('/path-a', {
        controller: 'ModuleAController',
        templateUrl: 'path/to/template.html',
        menuDisplay: true, // Custom parameter
        displayName: 'Solution Manager' // Custom parameter
      });
  });

模块B:

angular
  .module('module-b', [])

  .controller('MenuController', ['$scope', '$route',  function ($scope, $route) {
    var entries = [];
    angular.forEach($route.routes, function (route, path) {
      if ( route.menuDisplay == true ) {
        this.push({
          displayName: route.displayName,
          route: '#' + path
        });
      }
    }, entries);
    $scope.menu = entries;
  }]);

您可能会添加一些检查以确保提供displayName等等。