AngularJS module.constant():如何仅在模块内定义常量?

Eri*_*ria 7 javascript angularjs

在页面上,我有几个Angular模块.对于每个模块,我定义一个包含模块版本的常量.

var module1 = angular.module('module1').constant('version', '1.2.3');
var module2 = angular.module('module2').constant('version', '2.0.0');
...
Run Code Online (Sandbox Code Playgroud)

我虽然模块中定义了一个常量.但是当我在module1中使用常量时,我得到的值是'2.0.0'......

有没有办法定义一个适合模块的常量(或其他任何东西)?

编辑:对于替代解决方案,您能否解释一下如何使用它,例如在控制器声明中?

module2.controller('myCtrl', function( $scope, $http, $q, ..., version ){
    // Here I can use the constant 'version'
}
Run Code Online (Sandbox Code Playgroud)

And*_*CIO 6

一个非常好的问题.我能想到一个快速解决这个问题的方法:

angular.module('module1').constant('module1.version', '1.2.3');
angular.module('module2').constant('module2.version', '2.0.0');
Run Code Online (Sandbox Code Playgroud)

我不知道它有多适合你的需求.但我希望它有所帮助.

主要问题是Angular中的命名.您不能为服务/常量/值等具有相同的名称.它们将被覆盖.我用上面给你的"名称空间"解决了这个问题.

注入名称空间的示例:http://codepaste.net/5kzfx3

编辑:

对于您的示例,您可以像这样使用它:

module2.controller('myCtrl', ['$scope', '$http', '$q', ... , 'module2.version'], function( $scope, $http, $q, ..., version ){
    // Here I can use the constant 'version'
}
Run Code Online (Sandbox Code Playgroud)