在AngularJS中创建和访问全局常量

Creating and accessing a global constant in AngularJS

本文关键字:访问 全局 常量 创建 AngularJS      更新时间:2023-09-26

有人知道创建和访问全局常量的最佳方式是AngularJS吗?

我希望能够做这样的事情:

app.constant('baseURL','http://www.baseurl.com');

并从任何工厂或控制器访问

选择constant将是一种更好的方法,因为它有能力在config级别或provider中访问它,以便我们可以使用它们来携带配置级别设置。

对于使用,你可以像我们为service/factory注入一样注入,或者考虑任何依赖。

为了使它更好,你可以在你的app.constant中使用Object,这样它就可以携带多个设置。

<<p> 常数/strong>
app.constant('configSettings', {
   'baseUrl': 'http://www.baseurl.com',
   'someElseSetting': 'settingValue'
   //other setting will also be there.
}); 
控制器

app.controller('myCtrl', function($scope, configSettings){
   //console.log(configSettings.baseUrl);
   //you could use base URL here
});