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

ⅰ亾dé卋堺 提交于 2019-12-13 11:49:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!