Javascript AngularJS 动态注入作用域或控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14415845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:41:03  来源:igfitidea点击:

AngularJS dynamically inject scope or controller

javascriptangularjs

提问by Mass

Is it possible to inject scope or controller during running ? or any other advice to dynamically inject services into controller ?

是否可以在运行期间注入范围或控制器?或任何其他建议将服务动态注入控制器?

Application.controller('IndexController', function($scope){

    // some actions

    if(someconditions) {
            $scope.$inject = [someServiceName];
            // and here i want to use service methods 
    }

});

Thanks in advance

提前致谢

回答by Mark Rajcok

A service can be dynamically injected (by name) into a controller using the $injector. Being able to inject services via controller arguments is just a convenience that Angular provides. Under the hood, the $injector is used by Angular to retrieve object instances. But we can use the $injector ourselves also.

可以使用$injector将服务(按名称)动态注入到控制器中。能够通过控制器参数注入服务只是 Angular 提供的一种便利。在幕后,Angular 使用 $injector 来检索对象实例。但是我们也可以自己使用 $injector。

function MyCtrl($scope, $injector) {
  $scope.doSomething = function(someService) {
    var service = $injector.get(someService)  // someService contains the name of a service
    service.value += 10
}

Fiddle.

小提琴

回答by MechanicalCoder

Following is one use case i came across recently, I was trying to inject the a service "myService" in the Factoy and got the following error.

以下是我最近遇到的一个用例,我试图在 Factoy 中注入服务“myService”,但出现以下错误。

**Uncaught Error:** *[$injector:cdep] Circular dependency found: $http <- $modal <- myService <- interceptorFactory <- $http <- $templateRequest <- $compile*

[http://errors.angularjs.org/1.3.0/$injector/cdep?p0=%24http%20%3C-%20%24mod%E2%80%A6orFactory%20%3C-%20%24http%20%3C-%20%24templateRequest%20%3C-%20%24compile][1]

To solve this issue, $injector came as life saver

为了解决这个问题,$injector 来作为救命稻草

var service = $injector.get('myService') //this will create a dynamic service instance 

and now you can use the service in a similar way you have used other services in your application.

现在您可以像在应用程序中使用其他服务一样使用该服务。