Set global constants in AngularJs

杀马特。学长 韩版系。学妹 提交于 2019-12-11 08:38:25

问题


I am trying to create constants js file in angular js for an application. I am using below code to implement constants for entire application. It's working fine.

<code>
// app.js
angular.module('myApp', [
        'ngCookies',
        'ngResource',
        'ngSanitize',
        'ngRoute'
    ])
    .constant('config', {
        mySetting: 42
    })
    .config(function ($routeProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'views/main.html',
                controller: 'MainCtrl'
            })
            .otherwise({
                redirectTo: '/'
            });
    });
</code>

My concern is in app.js file I want to write only routing, for constants I want to write separate file and I will call same file for all the controllers in my application.

For entire application might be 200+ constants I want to declare, so I want to make it is separate file or split constants file for controllers wise.

Please guide me which way is easy for maintenance.

Thanks in advance


回答1:


You can define constants this way

app.value('config', {
   "key1": "value1",
   "key2": "value2"
});

and in controller you can access this way config.key1 OR config.key2. In this way you can define constants as may as you require.

Note: Do not forget to give reference/inject to config.

Regards




回答2:


You can also maintain a separate file by using another module to handle all your constant, factory, services or value. To handle your constants the below code will give you and idea

Eg:

include your app.js file after that your constant.js script file

var myApp = angular.module("myApp", ['myConstants']); //constants module injection
myApp.controller("myController", ["$scope", "myValue", function() {
....
}]);

in your constant.js

angular.module("myConstants", []).constant('myValue', 'The value');

For more understanding refer http://www.learn-angular.org/#!/lessons/handling-complexity




回答3:


Lets Assume you want to have a constant named serviceUrl in your application .here is a simple way

angular.module('myApp', ['ngRoute'])
.value('serviceUrl','http://localhost:8080/hello')

'ngRoute' is optional. ignore it in case your application is not using ngRoute.

Can access it inside a service as posting some data

angular.module('myApp').
service('myService', ['$http', 'serviceUrl',function($http,serviceUrl){
    this.getData= function(data){
        console.log(JSON.stringify(data));
        return $http({
            method: 'POST',
            url: serviceUrl
            data: data
        })

}}



来源:https://stackoverflow.com/questions/38366359/set-global-constants-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!