Can’t retrieve the injector from angular

Before answering the question we need to note that there is only one injector instance per application and not per module. In this sense it is not possible to retrieve an injector per module. Of course if we take the top-level module, it represents the whole application. In this sense, an application and top-level module seem equivalent. It might seem like a subtle difference but it is important to understand in order to fully and properly answer this question.

Next, from what I can understand you would like to retrieve the $injector and not create a new instance of it. The thing is that the angular.injector will create a new $injector instance for modules (an app) specified as arguments. Here the main AngularJS module (ng) must be specified explicitly. So, in this code example:

var injector = angular.injector(['gaad', 'components']);

you were trying to create a new injector from components defined in ‘gaad’ and ‘components’ modules and obviously $compileProvider is not defined in your custom modules. Adding the ng module to the list would “solve” the problem by creating a new injector – something that you probably don’t want to happen.

To actually retrieve an injector instance associated to a running application we can use 2 methods:

  • from within AngularJS JavaScript the simplest solution is just to inject $injector instance: http://docs.angularjs.org/api/angular.injector
  • from outside of AngularJS world – call angular.element([DOM element]).injector() where [DOM element] is a dome element where the ng-app was defined (or any child element of this element). More info here: http://docs.angularjs.org/api/angular.element

Here is the jsFiddle showing 2 methods of the injector retrieval: http://jsfiddle.net/xaQzb/

Please also note that using $injector directly is not very common scenario outside of unit testing. It might be useful thought for retrieving AngularJS services from outside of AngularJS world. More info here: Call Angular JS from legacy code.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)