gsanta
gsanta

Reputation: 774

Can I inject dependencies on the fly in angular.js?

I have the following service:

var module = angular.module('app', []);

module.service('service', function(dep){

});

And suppose that I need to instantiate it somewhere in my code, with a different dependency, than the default one.

    //service is injected with the default 'dep' dependency
module.controller('controller', function(service, $injector) {


   //I need to call the service with my custom dependency
   //but $injector does not help, because it only gives back
   //the already injected service object
   var injectedService = $injector.get('service')

   //So theoretically I would need something like this
   //but I did not find such a feature yet
   var customDep = {...}
   var serviceWithCustomDep = $injector.inject('service', [customDep]);
});

Is there a way to achieve this?

Upvotes: 0

Views: 839

Answers (1)

jcz
jcz

Reputation: 903

In short: use $injector.invoke function to invoke a function with dependencies injected.

Define a factory (or service) that will return a function which you will invoke with the dependencies you desire.

module.factory('myFactory', function () {
    return function () {
        //do stuff here with dependencies injected
    };
});

Then in your controller for example:

module.controller('MyController', function (myFactory, $injector) {
    //define the dependencies you want, for example:
    myFactory.$inject = ['$http', '$location'];
    $injector.$invoke(myFactory);
});

This way you can change the dependencies with which you invoke the myFactory function as you please, you only need to modify the $inject property of the function.

Here's a link with more info: https://docs.angularjs.org/guide/di

Upvotes: 1

Related Questions