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

Inject constant to other modules config using Angular JS

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

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

这适用于应用程序模块配置,但不适用于其他模块配置(对于其他模块上的控制器),我总是得到 "Unknown provider: info from 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>