Oliver Salzburg Oliver Salzburg - 1 month ago 9
AngularJS Question

How can I retrieve the injector for my application?

I'm trying to run a function and have services injected into it. I thought this could easily be accomplished using

$injector
. So I tried the following (simplified example):

angular.injector().invoke( [ "$q", function( $q ) { $q.something(); } ] );


Which results in
Uncaught Error: [$injector:unpr] Unknown provider: $qProvider <- $q
.

I know I can solve that by using
angular.injector( ["ng"] )
instead, but there are actually several more dependencies.

It would be perfectly fine, if I could just retrieve the injector instance that is used everywhere else in my application.

The documentation for
angular.injector
suggests that you can retrieve it with
angular.element(document).injector()
, but that results in
undefined
for me.

Answer

You shouldn't be needing this, but you can get your app's $injector using the root-element of your app (or any child element).
E.g., if you use ngApp on the body:

angular.element(document.body).injector();
Comments