Oliver Salzburg
Oliver Salzburg

Reputation: 22099

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.

Upvotes: 2

Views: 2447

Answers (3)

hewstone
hewstone

Reputation: 4715

ExpertSystem's answer worked perfectly for me

This works perfectly for me. I'm trying to invoke a function from an angular service outside the angular scope in the document "resume" event for use in my cordova application. Here is the code that I used

var injector = angular.element(document.body).injector(); //get the document
injector.invoke(['myService', function (myService) {
    myService.doSomething();
}]);

Upvotes: 1

gkalpak
gkalpak

Reputation: 48211

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();

Upvotes: 11

Mosho
Mosho

Reputation: 7078

Try this:

var $injector = angular.injector(['myApp','ng'])

For $location you need to bootstrap the app to the page (start the app):

var $injector = angular.bootstrap(document, ['myApp'])

This will return the injector every time you call it but won't create any conflicts if the script was already loaded.

Upvotes: 0

Related Questions