在AngularJS模块依赖项中包含全局配置

时间:2014-08-16 22:24:18

标签: angularjs dependencies browserify

我开发了一个AngularJS应用程序,该应用程序使用browserify并将模块作为依赖项注入主应用程序。在所有模块中,我希望能够从routingConfig.js文件访问全局配置。

部分代码:

主app.js

  var routingConfig = require('./common/config/routingConfig');

  module.exports = angular.module('app', [
    // modules as dependencies
    require('./home/home').name,
    require('./login/login').name
  ]);

module home.js

  var HomeCtrl = require('./homeController');

  module.exports = angular.module('app.home', [
    'home/home.tpl.html',
    'ui.router'
  ])
  .config(function config($stateProvider) {
    $stateProvider
      .state('home', {
        url: '/',
        controller: 'HomeCtrl',
        templateUrl: 'home/home.tpl.html',
        data: {
          pageTitle: 'Home'

          /**
           * I want to be able to use values from routingConfig here...
           */
        }
      });
  })
  .controller('HomeCtrl', ['$scope', HomeCtrl]);

我当然可以在每个模块中都需要routingConfig,这样就行了,但理想情况下,我希望能够只需要一次并在主应用程序及其模块中全局使用它。任何想法都会非常感激。

1 个答案:

答案 0 :(得分:2)

我想到了解决方案。

1)创建一个名为'app.config'的新模块,并使用角度常量服务(https://docs.angularjs.org/api/auto/service/ $ provide#constant)来注册和使用你的配置:

 var routingConfig = require('./common/config/routingConfig');

 module.exports = angular.module('app.config', [
 ])
 .constant('routingConfig', routingConfig);

2)将此“app.config”模块添加到app.js

中的模块依赖项列表中
 module.exports = angular.module('app', [
   // modules as dependencies
   require('./config/routingConfig').name,
   require('./home/home').name,
   require('./login/login').name
 ]);

3)您现在可以注入routingConfig并使用它:

 module.exports = angular.module('app.home', [
   'home/home.tpl.html',
   'ui.router'
 ])
 .config(function config($stateProvider, routingConfig) {

    ... use routingConfig here...
 });
相关问题