Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Injecting a factory / service with identical name but under different module

Let's say I have three factories of the same name DSerrorLog each under different module

angular.module('module1').factory('DSerrorLog', function () {
    return { show: false, msg: "" };
});
angular.module('module2').factory('DSerrorLog', function () {
    return { show: false, msg: "" };
});
angular.module('module3').factory('DSerrorLog', function () {
    return { show: false, msg: "" };
});

How do I inject the correct instances from the correct module one e.g. DSerrorLog under module3 into my controller? I suppose syntax such as module3.DSerrorLog won't work here.

angular.module('mainApp', ['module1', 'module2', 'module3'])
    app.controller('MainCtrl', function ($scope, DSerrorLog) {
});
like image 272
lolski Avatar asked Feb 06 '14 05:02

lolski


People also ask

Which of the following components can be injected as a dependency in AngularJS factory service value all of the above?

26) Which of the following components can be injected as a dependency in AngularJS? Answer: D is the correct answer. The "Application Module" can be injected as a dependency in AngularJS.

Which components can not be injected as a dependency in AngularJS application module constant value factory?

You cannot inject values into the module. config() function. Instead constants are used to pass values at config phase.

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.

How do I inject a service in AngularJS?

Injecting a value into an AngularJS controller function is done simply by adding a parameter with the same name as the value (the first parameter passed to the value() function when the value is defined). Here is an example: var myModule = angular. module("myModule", []); myModule.


1 Answers

Cool question!

It turns out that the order that you include them affects which one you get. Basically each module in add will overwrite the injector. So in your example DSerrorLog will be from module3 if you just inject it normally.

Turns out you can still get the injector for other modules if you want to use them. Here is a fiddle where I show how to do that: http://jsfiddle.net/7YH7p/

app.controller('myCtrl', ['$scope', '$injector', 'test', 
    function($scope, $injector, test) {
        $scope.injected = test.data;
        var inj = angular.injector(['mod1']);
        $scope.my_inject = inj.get('test').data;
}]);

The two have different values!

Hope this helped!

like image 146
hassassin Avatar answered Nov 15 '22 05:11

hassassin