AngularJS dynamically inject scope or controller

前端 未结 2 519
半阙折子戏
半阙折子戏 2020-12-07 12:03

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

Application.controller(\'         


        
相关标签:
2条回答
  • 2020-12-07 12:19

    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.

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

    Fiddle.

    0 讨论(0)
  • 2020-12-07 12:19

    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.

    **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

    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.

    0 讨论(0)
提交回复
热议问题