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.
You need to use $injector to get a service from a string:
$injector.get('Contact')['send'](email);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With