使用Angular JS将常量注入其他模块配置

mar*_*oss 36 javascript provider dependency-injection constants angularjs

我想在整个应用程序中共享一些变量,如基本路径.在模块配置期间,需要可以访问这些变量.我的意见是,我可以使用常量或提供者.

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

这适用于app-module-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);
//});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

我想我错过了一些细节,你有什么想法吗?

iku*_*men 51

您的info常量在myApp模块中定义.如果我正确理解你的问题,你想在其他模块中使用常量(例如myApp.orders模块).如果是这样,那么你需要将myApp注入myApp.orders,但看起来你想要反过来.一种解决方案是将常量分离为独立模块,并在需要时将其作为依赖项注入.

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

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

angular.module('myApp.orders', ['constants'])
  ...
Run Code Online (Sandbox Code Playgroud)

  • 我相信我在官方网站的评论中找到了我的问题的答案:_Modules可以将其他模块列为其依赖项.根据模块的不同,需要在加载需求模块之前加载所需的模块.换句话说,所需模块的配置块在需求模块的配置块之前执行.运行块也是如此.即使多个其他模块需要,每个模块也只能加载一次._ (3认同)