28

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.

1 Answer 1

45

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

Sign up to request clarification or add additional context in comments.

1 Comment

What if both modules are already injected on the main module?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.