0

I have a defined function.

$scope.myFunction=function(){
 alert("works")
}

I have a variable called $scope.myVar and this contains an string that is a function.

$scope.myVar="myFunction()";

How can I call the function directly from a variable ($scope.myVar) and not from the defined function($scope.myFunction)?

something like:

$scope.myVar();

this is my code..

http://jsfiddle.net/o0tuvyt2/

$scope.myFunction=function(){
 alert("works")
}

    $scope.myVar="myFunction()";

//Execute this:
//$scope.myVar() I dont know
yavg
  • 2,761
  • 7
  • 45
  • 115
  • as said in the answers, eval is a possibility.. but its unsafe and generally frowned upon to use eval unless you have a really good reason. Can you tell us more about your use case and why it has to be a string instead of just binding your variable to a function and invoking it the normal way? – James LeClair Jan 19 '18 at 16:19

5 Answers5

1

You could eval it. This attempts to parse the contents of a string into executable javascript:

eval($scope.myVar);
UncleDave
  • 6,872
  • 1
  • 26
  • 44
0

People tend to jump to eval, but the Function constructor is typically a better solution.

Either way there is probably a better solution overall within your use case. Evaluating JS from a string is typically a no-no except in the case of templating. Before implementing anything I would suggest looking at the situation you're trying to solve and try hard to look at it differently. Often times the first step to a better solution is realizing that you can look at a problem from a different perspective.

$scope = {};
$scope.myFunction=function(){
 alert("works")
}

    $scope.myVar= new Function("$scope.myFunction()")();
zfrisch
  • 8,474
  • 1
  • 22
  • 34
0

You can use window context to call your function :

window[$scope.myVar](arguments);

Don't use eval. It's very unsafe.

Full working example (with arguments and scope) :

$scope = {};
$scope.myFunction=function(text){
 alert(text);
}

$scope.myVar="myFunction";
$scope.myArgs="great job";


$scope[$scope.myVar]($scope.myArgs);

More details here : https://stackoverflow.com/a/359910/7415107

André DS
  • 1,823
  • 1
  • 14
  • 24
0

Similar question to this has already been posted.

Calling a JavaScript function named in a variable

If you read through this post you will see why you should not use eval.

Chris
  • 153
  • 2
  • 15
0

As everybody said, eval is very unsafe, but, if you really need to use it, it would be better if you use the angular version because it will evaluate your expression on the current $scope.

$scope.$eval($scope.myVar)

https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$eval

luisenrike
  • 2,742
  • 17
  • 23