Accessing factory defined in another module in angularjs

26,217

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

Share:
26,217
Sai_23
Author by

Sai_23

Updated on September 09, 2020

Comments

  • Sai_23
    Sai_23 over 3 years

    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.