使用Angular JS将常量注入其他模块配置
Inject constant to other modules config using Angular JS
我想在整个应用程序中共享一些变量,如基本路径。这些变量需要在模块配置期间可访问。我的观点是,我可以使用常量或提供者。
我有几个模块,每个模块都有自己的路由配置。在这些路由配置中,我想访问一些设置,例如。
这适用于应用程序模块配置,但不适用于其他模块配置(对于其他模块上的控制器),我总是得到"未知提供商:来自myApp.orders的信息"。
var myApp = angular.module('myApp', ['myApp.orders']);
myApp.constant('info', {
version : '1.0'
});
myApp.config(function(info) {
console.log('app config: ' + info.version);
});
myApp.controller('MyController', function (info) {
console.log('controller: ' + info.version);
});
var orders = angular.module('myApp.orders', []);
// Remove comments to see it fail.
//orders.config(function(info) {
// console.log('orders config: ' + info.version);
//});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" class="container" ng-controller="MyController">
</div>
我想我只是漏掉了一个小细节,你知道吗?
info
常量在myApp
模块中定义。如果我正确理解你的问题,你想使用其他模块中的常量(例如myApp.orders模块)。如果是这样的话,那么您需要将myApp注入myApp.orders,但看起来您想要做相反的操作。一种解决方案是将常量解耦到一个独立的模块中,并在需要时将其作为依赖项注入。
angular.module('constants', [])
.constant(...);
angular.module('myApp', ['constants', 'myApp.orders'])
...
angular.module('myApp.orders', ['constants'])
...
我不知道我的解决方案是否是最漂亮的,但我在index.html中放了一个CONFIG的定义,我从其他组件中引用了这个定义。我用服务器端代码生成了index.html,这样我就可以在程序启动时设置值。也就是说,我使用的是index.cshtml,但它和index.php或其他技术一样容易。以下是我的index.html:
....
<script type="text/javascript">
var usingMockDataGlobal = true;
</script>
....
<script type="text/javascript">
(function () {
'use strict';
var configData = {
codeCampType: 'angu',
loggedInUsername: 'peter',
mockData: usingMockDataGlobal
};
angular.module('baseApp').constant('CONFIG', configData);
})();
</script>
相关文章:
- 在BoilerplateJS浏览器加载所有脚本(在其他模块中),而不考虑激活的模块
- 将路由处理程序委托给NodeJS+Express中的其他模块
- 如何从指令中的其他模块调用方法
- 使用其他模块中的函数,避免异步回调地狱
- 其他模块中的节点事件发射器
- 使用Angular JS将常量注入其他模块配置
- 如何将全局变量放在Globals.js模块中,并在其他模块中访问它们
- 是否可以访问同一文件中的其他模块导出功能
- $window对象在其他模块中不可用
- RequireJS - 先初始化一个依赖模块,然后再加载其他模块
- Dojo构建没有't包括dojo/dom、dom/when、dojo/dom-class和大约100个其他模块
- require.js-无法加载任何其他模块
- Joomla下拉菜单在其他模块后面
- 如何使用Typescript / node.js让一个模块中的函数直接在其他模块中可用?
- 无法在expressJs的其他模块中导入app.js
- moment.js作为AMD模块加载时静默失败.其他模块都没问题
- 使用python电子邮件或其他模块在电子邮件中发送散景图
- 我如何创建一个变量,可以在其他模块中编辑,而不是全局
- Facebook JS SDK与其他模块:或者,为什么有Java代码的差异
- 在其他模块中使用require时获得未定义属性