Reputation: 211
I am passing the service name from one controller to another controller as argument in angularjs. When I receive that variable in the second controller and use it as service name then I get an error i.e. serviceNameVariable.get is not a function. So my question is that, How can I use a variable as service name in a controller ?
Upvotes: 1
Views: 412
Reputation: 27327
Look at Angular's $injector service which allows you to dynamically retrieve your own or native angular modules anywhere:
$injector
is used to retrieve object instances as defined by provider, instantiate types, invoke methods, and load modules.
We inject the $injector
service like any other:
app.controller('ctrl', function ($injector) {
var serviceNameVariable = '$http'; // or some input
var service = $injector.get(serviceNameVariable);
// Use the 'injected' service, in this case the $http#get method:
service.get('http://endpoint');
});
Upvotes: 0
Reputation: 11398
It's not that difficult to get a service by his name.
Dependency injection can also be done at runtime in angular :
angular.module("someApp").controller("childController", [
"$injector",
function($injector){
var serviceName = "someServiceName";
var service = $injector.get(serviceName);
service.executeAction(someParams);
}
]);
Upvotes: 3