72

我正在尝试构建一个 myApp.config 模块来存储我的应用程序的一些设置,我写了一个 config.js 文件:

angular.module('myApp.config', [])
    .constant('APP_NAME','My Angular App!')
    .constant('APP_VERSION','0.3');

我将它添加到我的 app.js(角度种子)中:

angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers', 'myApp.config']).

我将它添加到 index.html 文件中,现在我试图弄清楚如何在我的控制器中获取它,我尝试了:

angular.module('myApp.controllers', ['myApp.config'])
  .controller('ListCtrl', ['$scope', 'myApp.config', function($scope, $config) {
    $scope.printme = $config;
  }])

但我得到:

未知提供者:myApp.configProvider <- myApp.config

我可能在这里做错了什么,有什么想法吗?

4

4 回答 4

88

我认为在这样的注入中使用模块名称是无效的。不过,您可以简单地按名称注入常量:

angular.module('myApp.controllers', ['myApp.config'])
  .controller('ListCtrl', ['$scope', 'APP_NAME', function($scope, appName) {
     $scope.printme = appName;
}]);
于 2013-06-29T19:33:18.840 回答
73

我认为最简单的方法是使用对象文字添加一个常量。这适合我认为的大多数应用程序配置用例,因为它支持复杂的配置对象。在注册其他提供程序之前,该constant步骤也会提前运行。

angular.module('myApp').constant('cfg', {
  url: 'https://myapi.com/v1/',
  httpTimeout: 5000
})

要使用它,您只需注入cfg

angular.module('myApp').factory('user', function(cfg, $http){
  // cfg and $http together at last
})
于 2014-01-03T17:19:02.137 回答
5

还应该注意的是,SimplGy 的解决方案意味着“cfg”对象是一个常量,但该对象的属性不是。这意味着,您不能像这样重新分配“cfg”:

cfg = { randomProperty: randomValue };

您可以像这样重新分配“cfg”对象的属性:

cfg.url = 'BrandNewURL.com';
cfg.httpTimeout = 30;
于 2016-05-23T23:30:04.710 回答
3

查看此示例中常量的使用:

angular
.module('abp001App', ['ngRoute'])
.constant("myConfig", {
    "url": "http://localhost",
    "port": "80"
})
.config(function ($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'views/main.html',
            controller: 'MainCtrl'
        })
        .otherwise({
            redirectTo: '/'
        });
})
.controller('MainCtrl', function (myConfig) {
    // Do something with myConfig...
});
于 2017-04-26T14:06:26.360 回答