1

I've been working a lot lately with AngularJS and I really like the dependency injection stuff. I'm using it all over the place, but just in Angular components, like controllers and the like.

This always calls on the angular object:

angular.module('app').controller(/**/);

Now I have this function:

var custom = function(MyService) {
    // do stuff
};

I've declared the Service this way:

angular.module('app').factory('MyService', function($rootScope) {
    return {
        show: function() {
            // do stuff
                };
        },
        hide: function() {
            // do stuff
        }
    };
});

I now want to use this service in my custom function. Is there a way of manually calling the angular DI container? (I couldn't find anything in the docs...)

I know that this works for controllers not defined with the angular.module()... thing:

function Controller(MyService) {
    MyService.hide(); // works
}

But how to use it outside of AngularJS components, in completely independent functions?

Or do I have to take a completely different path to achieve my goal?

Cheers and thanks in advanced,

Christian

1 Answer 1

4

angularjs is pretty neat in the fact that it exposes its own internal services to the user. The service you're looking for is $injector

What you want to use to call your custom function is $injector.invoke(myCustomFunction,thisForCustomFunction,{named:locals});

If you are by chance wanting to invoke this function outside of angular you'll have to get the applications injector.

var injector = angular.element(elementWithNgApp).injector();

Note:

The invocation time may be reduced though. As the injector must annotate (find what services you need) using several regular expressions. The reason this is not an issue throughout angular is because it is done once. Because services,factories,providers, are all instantiated (newed) singletons that provide closure with the services and whatever uses the services inside your providers

To prevent this extra step you can provide a $inject property on your function.. Something like this:

myfunction.$inject = ['ServiceA','ServiceB'];
function myfunction(a,b){
    //a is ServiceA 
    //b is ServiceB
};
Sign up to request clarification or add additional context in comments.

2 Comments

Thats pretty awesome. Wasn' t aware of that. BTW: You can also use angular.injector() to get the injector.
angular.injector() will give you a new injector. Which won't have any of your services.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.