Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS dynamically inject scope or controller

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

like image 276
Mass Avatar asked Jan 19 '13 15:01

Mass


People also ask

Does AngularJS supports Dependency Injection?

Dependency Injection is pervasive throughout AngularJS. You can use it when defining components or when providing run and config blocks for a module.

How does AngularJS Dependency Injection work?

Dependency Injection in AngularJS can be defines as the software design pattern which defines the way the software components are dependent on each other. AngularJS provides a set of components that can be injected in the form of dependencies such as factory, value, constant, service, and provider.

Which component can be injected as Dependency in AngularJS?

26) Which of the following components can be injected as a dependency in AngularJS? Answer: D is the correct answer. The "Application Module" can be injected as a dependency in AngularJS.

What is controller inject in AngularJS?

Injecting a value into an AngularJS controller function is done simply by adding a parameter with the same name as the value (the first parameter passed to the value() function when the value is defined).


2 Answers

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.

like image 52
Mark Rajcok Avatar answered Oct 12 '22 23:10

Mark Rajcok


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.

like image 38
MechanicalCoder Avatar answered Oct 13 '22 00:10

MechanicalCoder