Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
1  
Have you tried something like eval("contact.send(email)");? –  Maverick Jul 18 '14 at 4:49
    
I was trying to avoid using eval, if at all possible. –  user2715324 Jul 18 '14 at 4:56
    
I ran into similar problem back in the day. This might help stackoverflow.com/questions/11666301/object-has-no-method-apply –  Maverick Jul 18 '14 at 5: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 5:01

2 Answers 2

up vote 0 down vote accepted

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

$injector.get('Contact')['send'](email);
share|improve this answer

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

share|improve this answer
    
How could I pass the email argument, unless assign it into the scope? –  runTarm Jul 18 '14 at 5: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('[email protected]') –  Chandermani Jul 18 '14 at 5:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.