Reputation: 573
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
.
Upvotes: 2
Views: 179
Reputation: 48968
Put the parseInt
function on $scope
and it works.
myApp.controller('MyCtrl', function($scope) {
$scope.parseInt = parseInt;
$scope.foo = function() {
return (parseInt("12px") * 2).toString() + "px";
}
});
With Angular Expressions, functions are fetched from $scope
instead of the global namespace.
From the Docs:
- Context: JavaScript expressions are evaluated against the global window. In Angular, expressions are evaluated against a scope object.
-- AngularJS Developer Guide -- Expressions
The DEMO on JSFiddle
Upvotes: 0
Reputation: 3718
{{}}
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.
Upvotes: 2
Reputation: 689
It's because you're trying to parse a string to integer with alpha characters in it, I guess javascript removes the characters for you, whereas angular keeps it literal.
(parseInt("12")*2).toString() + "px";
Would be the correct angular syntax.
Upvotes: 0