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

标签 angularjs dependencies browserify

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

部分代码:

主应用程序.js

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

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

模块 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) 创建名为“app.config”的新模块并使用 Angular 常量服务 (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) 您现在可以注入(inject) routingConfig 并使用它:

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

    ... use routingConfig here...
 });

关于angularjs - 在 AngularJS 模块依赖项中包含全局配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25344543/

相关文章:

javascript - 摘要循环显示我的数组没有变化(并且 View 不刷新)

java - Maven + ODL osgi.wiring.package javax

javascript `require` 而不是 Node.js 中的 Three.js 文件中的 html `script`

javascript - 从我的页面/html 需要(并将值传递给)browserify 模块

ios - flutter :错误:找不到 Getter: 'suspending' 。案例 AppLifecycleState.suspending

javascript - React 和 Grunt - Envify NODE_ENV ='production' 和 UglifyJS

javascript - "TypeError: Object doesn´t support this actionundefined"IE8 与 Angular 应用程序中的错误

javascript - 在我的情况下如何获取 json 数据?

angularjs - 防止在 angular.js 编译/插入文档之前暂时显示双花括号符号

c# - 有没有什么工具可以分析c#程序中变量之间的依赖关系?