如何将依赖注入AngularJS中的现有控制器

如何将依赖注入AngularJS中的现有控制器,angularjs,dependency-injection,Angularjs,Dependency Injection,我有一个在body元素上定义的控制器: app.controller('bodyController', ['$injection1', '$injection2', function($injection1, $injection2){ // doing stuff here }]); 现在在其他地方,我希望能够向这个控制器注入另一个依赖项。伪代码: app.controller('bodyController').inject(['$injection3', fun

我有一个在body元素上定义的控制器:

app.controller('bodyController', ['$injection1', '$injection2',
    function($injection1, $injection2){
        // doing stuff here
}]);
现在在其他地方,我希望能够向这个控制器注入另一个依赖项。伪代码:

app.controller('bodyController').inject(['$injection3', function($injection3){
    // doming more stuff here
});

这可能吗?

您可以在控制器中注入依赖项(
$injector
),然后在控制器中直接请求其他依赖项

app.controller('bodyController', ['$injection1', '$injection2', '$injector',
    function($injection1, $injection2, $injector){
      var injectorGet = $injector.get;
      //myService will be singleton instance of myService
      var myService = injectorGet('myService');
      //and injectorGet which you can get other dependency too.
}]);

您可以将
$injector
依赖项注入控制器内部&然后在控制器内部,您可以直接请求控制器中的其他依赖项

app.controller('bodyController', ['$injection1', '$injection2', '$injector',
    function($injection1, $injection2, $injector){
      var injectorGet = $injector.get;
      //myService will be singleton instance of myService
      var myService = injectorGet('myService');
      //and injectorGet which you can get other dependency too.
}]);

OP说在别的地方。我想这不可能是我的答案。因为在这种情况下,为什么不首先简单地注入
myService
?@SaeedNeamati我从问题中了解到,OP想要添加/访问第三个(其他)依赖项,这是他稍后想要添加的(这是我假设的),让我们看看OP想要什么。。他将对此发表评论。。如果我遗漏了什么,请纠正我。不过谢谢你提醒我……)@PankajParkar,我该怎么办?我是说其他地方的注射服务?我是说其他地方的注射服务?为什么不先注入?@SSH因为OP想要动态获取依赖对象,所以OP可能有这样的情况,有时他可能会在应用程序模块中添加
service/factory
,基于控制器中的某些条件,使用
$injector
依赖关系(我没有在DI数组中添加的原因是,当依赖项不在模块中时,它会抛出一个错误)OP在其他地方说。我认为这不能被回答。因为在这种情况下,为什么不首先简单地注入
myService
?@SaeedNeamati我从问题中了解到,OP想要添加/访问第三个(其他)依赖性,他稍后想添加(这是我假设的),让我们看看OP想要什么。他会对此进行评论。如果我遗漏了什么,请纠正我。尽管谢谢提醒:)@PankajParkar,我该怎么办?我是说其他地方的注入服务?我是说其他地方的注入服务?为什么不先注入?@SSH因为OP想要动态获取依赖对象,所以OP可能有这样的情况,有时他可能会在应用程序模块中添加
service/factory
,基于控制器中的某些条件,使用
$injector
依赖关系(我没有在DI数组中添加的原因是,当依赖项不存在时,它将抛出一个错误)