I have a main module main
which contains a service mainService
. I have then injected another module moduleA
in my main module. I randomly called mainService
in moduleA
without injecting main
module and was amazed to see it is working fine.
angular.module('main', ['moduleA']);
angular.module('main').service('mainService', function(){
//insert code here
});
angular.module('moduleA', []);
angular.module('moduleA').controller('abc', function(mainService){
//mainService available here, without injecting main module
});
I want to know the reason behind this. I once read in a comment that a service defined in a module is available everywhere in the application, but couldn't find the source. Is it ok to continue using it like this?
I'm using AngularJS ver 1.3.15
if it helps.
Yes you can use the service of main because of parent child relationship. "main" is a parent module and "moduleA" its child/dependency module.
Any serivce, controller, directive defined in "main" module will be available with "moduleA"
Lets understand this concept with a more complex scenario
angular.module('main', ['moduleA', 'moduleB']);
angular.module('moduleA', []);
angular.module('moduleA').service('moduleAService', function(){
//insert code here
});
angular.module('moduleB', []);
angular.module('moduleB').controller('abc', function(moduleAService){
//moduleAService available here, without injecting moduleA module
});
Now in this case moduleA and moduleB are totally independent but still moduleB can access moduleA services
It is because main module is dependent on moduleA and moduleB. So moduleA services is injected in main module and moduleB being a child of "main" module can access it.
Injecting something like a service in the parent, makes it available to all its children.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With