在angularJS中覆盖模块值/常量的最佳方法 [英] Best way to override module values/constants in angularJS
问题描述
我在angularJS中编写了一个封装所有后端通信的模块。为了获得更大的灵活性,我将api前缀作为模块的常量值(可能是值,因为我在配置阶段没有使用它)。
所以类似
I have written a module in angularJS that encapsulates all the backend communications. For greater flexibility I have the api prefix as a constant value on the module (could be value since I am not using it in the config phase). so something like
angular.module('myapp.data').constant('apiPrefix', '/api/data');
现在我想从两个不同的应用程序中使用这个模块。一个使用/ api1 / data和另一个/ api2 / data,我想在应用程序的配置阶段更改它。
我知道如何与提供商这样做,但让一个提供商持有一个价值似乎对我来说太过分了。我可以从应用程序配置阶段修改已使用的模块常量或值吗?
Now I want to use this module from two different applications. One uses /api1/data and the other one /api2/data and I would like to change this during the config phase of the application. I know how to do that with a provider, but having a provider to hold a value seems like an overkill to me. Can I modify used modules constants or values from the application config phase?
类似于:
angular.module("data", [])
.value('apiPrefix', '/api/data')
.factory('display', function(apiPrefix){
return {
pref: function(){
console.log(apiPrefix);
return apiPrefix;
}
}
});
angular.module("myApp",['data'])
.config(['apiPrefix', function(prefix){
prefix = 'https:/api/data';
}])
.controller("Example", function($scope, display) {
$scope.prefix = display.pref;
});
推荐答案
要覆盖模块值,可以重新定义角度后来的模块中的值。我相信它不应该是模块配置时间。
to override the module values, you can redefine the angular value in later modules. I believe it should not be done module config time.
angular.module("data", [])
.value('apiPrefix', '/api/data')
.factory('Display', function(apiPrefix){
return {
pref: function(){
return apiPrefix;
}
}
});
angular.module('myapp', ['data'])
.value('apiPrefix', '/api2/data')
.controller('MainCtrl', function($scope, Display) {
$scope.name = Display.pref();
});
在这里查看plunker:
http://plnkr.co/edit/k806WE
see the plunker here: http://plnkr.co/edit/k806WE
同样的事情也适用于角度常数。
same thing is applicable for angular constants too.
这篇关于在angularJS中覆盖模块值/常量的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!