Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Before answering the question we need to note that there is <strong>only one injector instance per application and not per module</strong>. 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.</p> <p>Next, from what I can understand you would like to <em>retrieve</em> the <code>$injector</code> and not create a new instance of it. The thing is that the <code>angular.injector</code> will create a new <code>$injector</code> instance for modules (an app) specified as arguments. Here the main AngularJS module (ng) must be specified explicitly. So, in this code example:</p> <pre><code>var injector = angular.injector(['gaad', 'components']); </code></pre> <p>you were trying to create a new injector from components defined in 'gaad' and 'components' modules and obviously <code>$compileProvider</code> is not defined in your custom modules. <strong>Adding the <code>ng</code> module to the list would "solve" the problem by creating a new injector</strong> - something that you probably don't want to happen.</p> <p><strong>To actually retrieve an injector instance associated to a running application</strong> we can use 2 methods:</p> <ul> <li>from within AngularJS JavaScript the simplest solution is just to inject <code>$injector</code> instance: <a href="http://docs.angularjs.org/api/angular.injector" rel="noreferrer">http://docs.angularjs.org/api/angular.injector</a></li> <li>from outside of AngularJS world - call <code>angular.element([DOM element]).injector()</code> where [DOM element] is a dome element where the <code>ng-app</code> was defined (or any child element of this element). More info here: <a href="http://docs.angularjs.org/api/angular.element" rel="noreferrer">http://docs.angularjs.org/api/angular.element</a></li> </ul> <p>Here is the jsFiddle showing 2 methods of the injector retrieval: <a href="http://jsfiddle.net/xaQzb/" rel="noreferrer">http://jsfiddle.net/xaQzb/</a></p> <p>Please also note that using <code>$injector</code> 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: <a href="https://stackoverflow.com/q/10490570/1418796">Call Angular JS from legacy code</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload