Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does angularjs treates null as $scope.null?

Example for the question

<div ng-show="bar !== null">hello</div>

Is this evaluated in the scope as

$scope.bar !== null

or is it as this?

$scope.bar !== $scope.null

Note that in last case, $scope.null would be undefined and the example would seem to work right.

Bonus:

if bar = null then this happens

// this does not work (shows hello)
<div ng-show="bar !== null">hello</div>

does not give the same result as

// this works ok (does not show hello)
<div ng-show="bar != null">hello</div>

why does that happen?

like image 871
jperelli Avatar asked Dec 19 '22 02:12

jperelli


2 Answers

Angular uses advanced parser ($parse service) in order to process and evaluate attribute expressions as if they were javascript code. When it works it will rank null higher priority over scope property with the same name. It means that in expressions like

ng-show="bar !== null"

Angular will indeed treat null as primitive null value.

It is however easy to instruct Angular that you want to use scope property and not null primitive. In this case you need to use bracket notation:

ng-show="bar !== this['null']"

And final note. While it's possible to use properties with names like null, undefined etc, I would not recommend it because it's confusing and you need to go with verbose bracket syntax.

like image 135
dfsq Avatar answered Dec 29 '22 17:12

dfsq


No, Angular recognizes some JS primitives in expressions, and null is among them.

like image 37
Estus Flask Avatar answered Dec 29 '22 16:12

Estus Flask