问题
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) {
});
回答1:
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!
来源:https://stackoverflow.com/questions/21594441/angularjs-injecting-a-factory-service-with-identical-name-but-under-different