styopdev styopdev - 6 months ago 12
AngularJS Question

How to get angular.js module's value from another module

I have two modules in my angular.js app.
In module1 (example name) I have a value defined like

angular.module('module1')
.value('ID', '')
.service('someService', function(ID) {
this.getId = function() {
return ID;
}
this.setId = function(id) {
ID = id;
}
})


I would like to access module1's ID value in module2.
I can access module1 from module2 using
`

angular.module('module1')


log in console will be`

Object {_invokeQueue: Array[39], _configBlocks: Array[1], _runBlocks: Array[1], requires: Array[8], name: "module1"}


when I try to access ID value or someService using

angular.module('module1').service("someService");


or

angular.module('module1').value("ID");


I am getting strange object looks like

Object {_invokeQueue: Array[40], _configBlocks: Array[1], _runBlocks: Array[1], requires: Array[8], name: "module1"}


Also I can't include module1 in the module2 on initialization, using this style

angular.module('module2', ['module1']);


because I already have module2 included in module1

angular.module('module1', ['module2']);

Answer

You still need to inject it as a dependency as you would with a controller or service etc.

If you wanted to access it in a controller you could have code similar to this

angular.module('module2').controller('MyExistingCtrl', ['ID', function(ID){
    console.log(ID);
}]);

Or, following John Papa's styleguide:

angular.module('module2').controller('MyExistingCtrl', MyExistingController)

MyExistingController.$inject = ['ID'];

function MyExistingController(ID){
    console.log(ID);
}

Read more on dependency injection.

Also it is explained on the angular documentation for providers. Scroll down the "Value Recipe" section.

Comments