我开发了一个 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/