AngularJS:注入具有相同名称但在不同模块下的工厂/服务 [英] AngularJS: Injecting a factory / service with identical name but under different module
问题描述
假设我有三个同名的工厂DSerrorLog
,每个工厂都在不同的模块下
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: "" };
});
如何从正确的模块一中注入正确的实例,例如module3
下的 DSerrorLog
进入我的控制器?我想像 module3.DSerrorLog
这样的语法在这里不起作用.
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) {
});
推荐答案
很酷的问题!
事实证明,您包含它们的顺序会影响您获得的顺序.基本上 add 中的每个模块都会覆盖注入器.因此,在您的示例中,DSerrorLog 将来自 module3,如果您只是正常注入它.
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.
事实证明,如果您想使用其他模块,您仍然可以获得它们的注入器.这是我展示如何做到这一点的小提琴:http://jsfiddle.net/7YH7p/>
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;
}]);
两者价值不同!
希望这有帮助!
这篇关于AngularJS:注入具有相同名称但在不同模块下的工厂/服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!