Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 988
user2715324 Avatar asked Dec 14 '22 21:12

user2715324


2 Answers

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

$injector.get('Contact')['send'](email);
like image 90
Jason Watmore Avatar answered Dec 28 '22 05:12

Jason Watmore


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

like image 42
Chandermani Avatar answered Dec 28 '22 05:12

Chandermani