我可以在angular.js中动态注入依赖项吗?

时间:2015-03-23 20:30:00

标签: angularjs

我有以下服务:

var module = angular.module('app', []);

module.service('service', function(dep){

});

并且假设我需要在我的代码中的某个地方实例化它,具有与默认依赖项不同的依赖项。

    //service is injected with the default 'dep' dependency
module.controller('controller', function(service, $injector) {


   //I need to call the service with my custom dependency
   //but $injector does not help, because it only gives back
   //the already injected service object
   var injectedService = $injector.get('service')

   //So theoretically I would need something like this
   //but I did not find such a feature yet
   var customDep = {...}
   var serviceWithCustomDep = $injector.inject('service', [customDep]);
});

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:1)

简而言之:使用$injector.invoke函数来调用注入了依赖项的函数。

定义一个工厂(或服务),它将返回一个你将使用你想要的依赖项调用的函数。

module.factory('myFactory', function () {
    return function () {
        //do stuff here with dependencies injected
    };
});

然后在您的控制器中,例如:

module.controller('MyController', function (myFactory, $injector) {
    //define the dependencies you want, for example:
    myFactory.$inject = ['$http', '$location'];
    $injector.$invoke(myFactory);
});

通过这种方式,您可以根据需要更改调用myFactory函数的依赖关系,只需要修改函数的$inject属性。

以下是包含更多信息的链接:https://docs.angularjs.org/guide/di

相关问题