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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With