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
  • 41
  • 1
  • 4

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,589
  • 12
  • 85
  • 88
  • 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,521
  • 2
  • 32
  • 36