Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
38
rated 0 times [  45] [ 7]  / answers: 1 / hits: 33244  / 12 Years ago, sat, january 19, 2013, 12:00:00

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


More From » angularjs

 Answers
62

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.


[#80759] Thursday, January 17, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
miles

Total Points: 256
Total Questions: 111
Total Answers: 104

Location: Benin
Member since Fri, Mar 24, 2023
1 Year ago
;