AngularJS dynamically injects scope or controller

Can I enter an area or controller during operation? or any other recommendations for the dynamic implementation of services in the controller?

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

Thank you in advance

+15
javascript angularjs
Jan 19 '13 at 15:30
source share
2 answers

A service can be dynamically injected (by name) into the controller using the $ injector . The ability to enter services through controller arguments is just a convenience that Angular provides. Under the hood, the $ injector is used by Angular to retrieve instances of the object. But we can also use the $ 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

+59
Jan 19 '13 at 20:11
source share

Below is one case that I recently encountered, I tried to enter the "myService" service in Factoy and received 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 problem, $ injector became a lifeguard

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

and now you can use this service in the same way as you used other services in your application.

+4
Apr 23 '15 at 9:56
source share



All Articles