Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: is 0 == 2? [duplicate]

Tags:

angularjs

I am scratching my head here. I am using angularJS and trying to use the expression that contains call to parseInt.

{{0 == 2}}  

...prints out false as expected.)

However, when I am trying:

{{parseInt(0) == parseInt(2)}} 

... it prints out... true !

How can this be possible?

like image 238
jazzblue Avatar asked Jun 15 '16 04:06

jazzblue


4 Answers

Angular does not use JavaScript's eval() to evaluate expressions. Instead Angular's $parse service processes these expressions.

Angular expressions do not have access to global variables like window, document or location. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs.

Refer

In your html

Both parseInt(0) and parseInt(2) are undefined in your html.

So {{undefined==undefined}} is true.Beacause parseInt is a Javascript function.So you cant access the parseInt function in side {{}}. [Here parseInt is not a scope variable]

Solution

If you wish to do this,

define parseInt in your controller,

$scope.parseInt = parseInt;

Then you can use the parseInt method in your html

like image 165
Muhsin Keloth Avatar answered Nov 12 '22 03:11

Muhsin Keloth


That's because parseInt is not defined in your scope.

http://jsfiddle.net/halirgb/Lvc0u55v/

like image 27
CD.. Avatar answered Nov 12 '22 02:11

CD..


You can't execute regular JS in an angular expression. Your expressions will be evaluated against the current scope. So, parseInt is undefined in the current scope.

If you set parseInt as a function reference, it will work.

$scope.parseInt = parseInt;
like image 41
Charlie Avatar answered Nov 12 '22 03:11

Charlie


This is because the view is attached to the controller via scope.

So whatever we write in view either a variable or a function or anything it's rendered by appending $scope in front of it.

eg. a is rendered as $scope.a in the view

So when we write parseInt, its rendered by $scope.parseInt which is not defined.

FIX- define $scope.parseInt = parseInt in the controller attached to the particular view

like image 1
Rohit Avatar answered Nov 12 '22 03:11

Rohit