Search code examples
angularjseval

$scope.$eval(stringFormula) is throwing errors in AngularJS


I have a project which is client solution based on angularJS calling an API. Formulas that should run on client solution are retrieved from the API, and parameters of each formula will be replaced by values entered by the client user.

Formulas are a bit complicated, not a simple addition or division.... Example:

"if('rented' == 'owned')
    { return     50 + 25;
}  else if( 'rented' == 'rented')
     {return    25;}
  else
   {  return   '' ;
}"

In order to execute this String it was suggested to use $scope.$eval(string). I have tried it with some simple params like $scope.$eval('1 + 2') and it worked successfully. But with the above example it is throwing parsing errors like this one:

The complete angularJS function in the controller is the below:

$scope.calulateFormula = function (formula) {

     formula = formula.replace(/\[P1]/g, $scope.param1.value);
     formula = formula.replace(/\[P2]/g, $scope.param2.value);

     return $scope.$eval(formula);
 }

In HTML page:

<tr ng-repeat="formula in lstFormulas">                           
   </td> 
       <td ng-bind="calulateFormula(formula)">
   </td> 
 </tr>

lstFormulas is retrieved from the API.

So how can I fix this issue and make formulas run on my webPage?


Solution

  • If you can replace all variables with values from scope, you can then use plain js:

    var f = new Function(formula);
    console.log(f());