Search code examples
javascriptangularjsangularjs-scopeangularjs-service

Convert String to Function in AngularJS


I am trying to convert strings to AngularJS Service method calls in a controller. For example, I would like to convert the string "Contact.send(email)" to call an existing service method. I thought to use:

window["Contact"]["send"](email);

as in this thread - How to execute a JavaScript function when I have its name as a string - but it says that the Contact service is undefined, despite being injected into the controller.


Solution

  • You need to use $injector to get a service from a string:

    $injector.get('Contact')['send'](email);