使用Angular JS向其他模块configuration注入常量

我想在整个应用程序中共享一些variables,如基本path。 这些variables需要在模块configuration期间进行访问。 我的意见是,我可以使用一个常数或提供者。

我有几个模块,每个模块都有自己的路由configuration。 在这些路由configuration中,我想访问一些设置,例如。

这适用于应用程序模块configuration,但不适用于其他模块configuration(对于其他模块的控制器),我总是会得到“未知提供者:来自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,但是看起来你想要做相反的事情。 一种解决方法是将常量解耦为独立模块,并在需要时将其作为dependency injection。

 angular.module('constants', []) .constant(...); angular.module('myApp', ['constants', 'myApp.orders']) ... angular.module('myApp.orders', ['constants']) ... 

我不知道如果我的解决scheme是最漂亮的,但我把我的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>