简体   繁体   中英

Using global variable (config.js) in angularjs module

angular.module('starter.services', [])
.controller('Friends', function() {
console.log(global);
})

angular.module('starter.anotherServices', [])
.factory('Friends', function() {
console.log(global);
})

Says I have few files for controller, factory and so on, how do I make a global variable that can be access by all of them? I have to create a .js file which will act as config like db credential and http request key.

You can use constant.

angular.module('starter.services', [''])
    .constant("global", {
        "test": "1",
    })

Now inject this global in all controllers and use it.

module.controller('Friends', function(global) {
console.log(global);
})

You can create constant and inject where ever you want to access.

var app = angular.module('yourModule', []);
app.constant('Global', {
  baseUtl: 'www.google.com'
});

app.config(function(Global) {
  console.log(Global);
});
app.controller('YourController', function(Global) {
  console.log(Global);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM