Javascript 从单独的JS文件检索常量\字符串值
我正在开发一个AngularJS应用程序。 我想知道在代码中包含字符串值的最佳实践是什么Javascript 从单独的JS文件检索常量\字符串值,javascript,jquery,angularjs,string,Javascript,Jquery,Angularjs,String,我正在开发一个AngularJS应用程序。 我想知道在代码中包含字符串值的最佳实践是什么 我计划使用另一个包含所有常量值的JS文件。我将在每个JS(控制器)中调用此JS文件,以引用字符串值。您可以像 angular.module('moduleName',[]).constant('constName',string|object|array); 您可以在指令或控制器或任何您想要的地方注入 angular.module('moduleName',[]).directive('directive
我计划使用另一个包含所有常量值的JS文件。我将在每个JS(控制器)中调用此JS文件,以引用字符串值。您可以像
angular.module('moduleName',[]).constant('constName',string|object|array);
您可以在指令或控制器或任何您想要的地方注入
angular.module('moduleName',[]).directive('directiveName', ['constName', function(constName){...});
Angular具有提供常数的内置方式,例如:
angular.module('foo', ['ngRoute']) // Your angularjs module
// Decide a name for the bucket of constants, then just declare the
// constants in turn as an object literal:
.constant("HTTP_CONSTANTS", {
"URL": "http://localhost",
"PORT": "80"
})
然后,您可以使用依赖项注入将其加载到您有权访问的任何地方,即foo
模块,即:
angular.module('foo')
.controller('bar', function (HTTP_CONSTANTS) {
... // Use HTTP_CONSTANTS.URL or HTTP_CONSTANTS.PORT, for example
})
下面是一个关于使用常量的好入门:
以下是示例代码
var app = angular.module('plunker', []);
app.constant('configs', {host:'localhost',port:8080});
app.controller('MainCtrl', function($scope, configs) {
$scope.name = configs.host;
});
这里是演示您有几个选项 全局值。您可以使用javascript对象形式的常量,该对象可以在整个应用程序中全局访问。例如,您的文件可能如下所示:
config = {
host: 'domain',
port: '1234'
};
angular.module('app.config', []).constant('config', {
host: 'domain',
port: '1234'
});
明显的缺点是,这些值不是真正的常量,很容易更改,所以很容易出错
角度配置模块。更可靠、更简洁的选择是创建一个单独的模块,用作主应用程序模块的依赖项。对于常数,您仍然有单独的文件,但该文件将保存具有常数服务的角度模块,而不是某些全局变量。大概是这样的:
config = {
host: 'domain',
port: '1234'
};
angular.module('app.config', []).constant('config', {
host: 'domain',
port: '1234'
});
然后在主应用程序中,您可以像
angular.module('app', ['app.config']).config(function(config) {
// console.log(config);
});
为此,您可以使用factory并在任何需要这些常量的地方注入此factory
var app=angular.module('Myapp', []);
app.factory('ConstantService', function(){
var constant={temp:'c'};
var getConstants=function(){
return constant;
};
return{
constants:getConstants;
}
});
app.controller('MyController',['ConstantService' function (ConstantService){
var constant= ConstantService.constants;
}]);
选中此选项,您可以将它们存储在JSON文件中,并在需要时通过AJAX获取。