Kenkron Kenkron - 27 days ago 6
AngularJS Question

Angular expressions resolve differently than the console

I have an expression that runs differently in javascript than in angular's {{expressions}}. Can anyone tell me why?

expression:

(parseInt("12px")*2).toString()+"px"


Evaluated in javascript, it resolves to
24px
. In an angular expression, it's
NaNpx
.

jsfiddle

Answer

{{}} tell Angular that in your view, you have an Expression to interpolate. Angular expressions do not support all of JavaScript. For documentation check here

If you need all of JavaScript. It is better to wrap the logic in a controller function.

Excerpt from docs:

It might be tempting to think of Angular view expressions as JavaScript expressions, but that is not entirely correct, since Angular does not use a JavaScript eval() to evaluate expressions. You can think of Angular expressions as JavaScript expressions with following differences:

Attribute Evaluation: evaluation of all properties are against the scope doing the evaluation, unlike in JavaScript where the expressions are evaluated against the global window.

Forgiving: expression evaluation is forgiving to undefined and null, unlike in JavaScript, where trying to evaluate undefined properties can generate ReferenceError or TypeError.

No Control Flow Statements: you cannot do any of the following in angular expression: conditionals, loops, or throw.