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

AngularJS dynamically inject scope or controller

本文关键字:控制器 作用域 注入 动态 AngularJS      更新时间:2023-09-26

是否可以在运行过程中注入作用域或控制器?或者有其他建议来动态地向控制器注入服务吗?

Application.controller('IndexController', function($scope){
    // some actions
    if(someconditions) {
            $scope.$inject = [someServiceName];
            // and here i want to use service methods 
    }
});

Thanks in advance

服务可以通过$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
}

小提琴。

以下是我最近遇到的一个用例:我试图在Factoy中注入a服务"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]

为了解决这个问题,$injector出现了

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

,现在你可以像在应用程序中使用其他服务一样使用该服务了