1

How do I evaluate the mathematical expression within a string and assign it to a numerical value in angularJS?

Eg: var value = 10;

var someValue = "Math.min(value * 0.22, 106800)". I need someValue to be a valid integer of 2.2.

Is this something which can be done by angularJS?

2 Answers 2

4

One way of doing this would be by injecting 'Math' into your scope and using it in say a controller

$scope.Math = window.Math;

Here's a fiddle: http://jsfiddle.net/bxE79/1/

Sign up to request clarification or add additional context in comments.

1 Comment

i like your solution better. you could run Math functions from the scope as well.. like this. jsfiddle.net/ayDAn
2

Use eval.

var value = 10;
var someValue = eval("Math.min(value * 0.22, 106800)");
console.log(someValue);

And it will be printed in console 2.2

1 Comment

I would highly suggest not doing this if it's a dynamic string from user input. You might consider using Angular's $eval method instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.