Sai_23
Sai_23

Reputation: 427

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.

Upvotes: 28

Views: 26687

Answers (1)

cuongle
cuongle

Reputation: 75306

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

Upvotes: 45

Related Questions