Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 877
Sai_23 Avatar asked Sep 04 '13 06:09

Sai_23


People also ask

Can we have multiple modules in AngularJS?

Yes, you can define multiple modules in angularJS as given below. The modularization in AngularJS helps us to keep the code clarity and easy to understand, as we can combine multiple modules to generate the application.

What is the difference between a service () and a factory ()?

factory() is a method that takes a name and function that are injected in the same way as in service. The major difference between an AngularJS service and an AngularJS factory is that a service is a constructor function and a factory is not.

Which is valid for AngularJS module?

13) Which of the following syntax is used to create a module in AngularJS? Answer: C is the correct option. To create a module in AngularJS, we use angular. module("app", []); syntax.

What is Factory in AngularJS with example?

Factory is an angular function which is used to return the values. A value on demand is created by the factory, whenever a service or controller needs it. Once the value is created, it is reused for all services and controllers. We can use the factory to create a service.


1 Answers

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

like image 171
cuongle Avatar answered Sep 19 '22 13:09

cuongle