Sai_23 Sai_23 - 3 months ago 10
AngularJS Question

Accessing factory defined in another module in angularjs

Can we call the factory functions defined in one module from another module? If so, how?

Let's say my first module is defined in

moduleOne.js
file as:

var myModule = angular.module('MyServiceModuleOne', []);
myModule.factory('notify', function () {
return {
sampleFun: function () {
// some code to call sampleFunTwo()
},
};
});


And my second module in
moduleTwo.js
as:

var myModuleTwo = angular.module('MyServiceModuleTwo', []);
myModuleTwo.factory('notifytwo', function () {
return {
sampleFunTwo: function () {
//code
},
};
});


How to call
sampleFunTwo()
from
sampleFun()
?

Thanks.

Answer

You need to inject MyServiceModuleTwo into MyServiceModule:

var myModuleTwo= angular.module('MyServiceModuleTwo',[]);
var myModule= angular.module('MyServiceModuleOne', ['MyServiceModuleTwo']);

Then inject notifytwo into notify:

myModule.factory('notify', function(notifytwo) {
    return {
        sampleFun: function() {
            notifytwo.sampleFunTwo();
        }      
    };
});


myModuleTwo.factory('notifytwo', function() {
    return {
        sampleFunTwo: function() {
            alert('From notify two');
        }    
    };
}); 

And the code on plunker