2

I call a function

getData('serviceName', 'functionName')

That function looks like

function getData(service, functionName){
    service.functionName(request, $root.thing).then()
}

But I always get service.function is not a function, how do I call them properly?

fiddle

11
  • Have you returned functionName from your service?? Is a factory or service ? Commented Sep 27, 2016 at 12:23
  • @Davide I pass the proper parameters, if that's what you're asking. Also console.log(service) and console.log(functionName) give me proper values. Yea it's a factory. Commented Sep 27, 2016 at 12:24
  • What is .then ? Is a promise? Uhm are you sure that you return that function from your service? You are in controller when you call getData so? If you can provide a plunker we can help you better Commented Sep 27, 2016 at 12:26
  • I've edited the fiddle with the service and with the main controller part, I hope it helps. Commented Sep 27, 2016 at 12:36
  • myService is a string. It is not a real service. It doesn't have findData method. Please, provide full code and not the excerpts, so it would be possible to note what exactly should be fixed in your code. Commented Sep 27, 2016 at 12:39

2 Answers 2

2

If you use bracket notation you can achieve what you want

function getData(service, functionName){
    service[functionName](request, $root.thing).then()
}
Sign up to request clarification or add additional context in comments.

Comments

0
function getData(service, functionName){
  var yourservice = $injector.get(service);
  yourservice.yourActualfunctionName(request, $root.thing).then() 
}    

You can sure use your service as string ,Use it like this.Make sure you inject $injector wherever you are using it. not sure about function name because function is not in same file.

3 Comments

eval() is never the answer, especially since the language supports this with brackets: yourService[functionName](...)
Yeah , you are right. My bad :( but this is the correct way to use service as string I think.
The brackets did the thing, but I have to keep the service name static.

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.