如何在不同的文件中为Angular JS定义常量

Ani*_*Sau 4 javascript iife angularjs

我想为我的Angular JS应用程序编写几个常量.我想将它们写在一个单独的文件中,并希望访问它们.

我试过像这样的IIFE(立即调用函数表达式),

constants.js

var Constants = (function () {

    var allConstants = {
        "url": 'abc',
        "name": "anijit",
        "sn": "sau"
    }

    return allConstants
})();
console.log('defined constants', Constants)
Run Code Online (Sandbox Code Playgroud)

但是当我试图访问它们时,它显示Constants not defined错误.我做错了什么?

我想Constants.url在途中使用它们,我不想$http打电话或类似的东西.怎么实现呢?

Sid*_*dey 10

因此,您使用的是AngularJS,您可以使用Constant Service.作为常量可以注入任何地方,包括angularjs应用程序中的配置调用.

此外,顾名思义,常量是固定的,它们在其他提供方法之前应用.有关更多详细信息,请参阅$ provide.constant().

// Storing a single constant value
var app = angular.module('myApp', []);

app.constant('appName', 'My App');

// Now we inject our constant value into a test controller
app.controller('TestCtrl', ['appName', function TestCtrl(appName) {
    console.log(appName);
}]);

// Storing multiple constant values inside of an object
// Note: values in the object mean they can be modified
var app = angular.module('myApp', []);

app.constant('config', {
    appName: 'My App',
    appVersion: 1.0,
    apiUrl: 'http://www.facebook.com?api'
});

// Now we inject our constant value into a test controller
app.controller('TestCtrl', ['config', function TestCtrl(config) {
    console.log(config);
    console.log('App Name', config.appName);
    console.log('App Name', config.appVersion);
}]);
Run Code Online (Sandbox Code Playgroud)