DAG
DAG

Reputation: 6994

AngularJS DI for custom functions

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

Upvotes: 1

Views: 482

Answers (1)

calebboyd
calebboyd

Reputation: 5753

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
};

Upvotes: 4

Related Questions