4

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.

Community
  • 1
  • 1
user2715324
  • 43
  • 1
  • 4
  • 1
    Have you tried something like `eval("contact.send(email)");`? – AdityaParab Jul 18 '14 at 04:49
  • I was trying to avoid using eval, if at all possible. – user2715324 Jul 18 '14 at 04:56
  • I ran into similar problem back in the day. This might help http://stackoverflow.com/questions/11666301/object-has-no-method-apply – AdityaParab Jul 18 '14 at 05:00
  • We need more code to go on. Why are you trying to reference `Contact` on `window` if it was injected into your controller? Post your controller and the service returning `Contact` please. – Chev Jul 18 '14 at 05:01

2 Answers2

6

You can use the $scope.$eval method to evaluate an expression on the current $scope context.

$scope.$eval("Contact.send(email)");

but you need to make sure that the Contact object is available on the $scope object, else it would not work. See scope documentation for this https://code.angularjs.org/1.2.15/docs/api/ng/type/$rootScope.Scope

Chandermani
  • 42,389
  • 11
  • 84
  • 86
  • How could I pass the email argument, unless assign it into the scope? – runTarm Jul 18 '14 at 05:11
  • Yes everything is evaluated in context of the scope only. If need to pass email argument either add it to scope or use the acual email such as `send('mymail@test.com')` – Chandermani Jul 18 '14 at 05:13
6

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

$injector.get('Contact')['send'](email);
Jason Watmore
  • 4,362
  • 2
  • 30
  • 36