问题
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?
回答1:
No, Angular recognizes some JS primitives in expressions, and null is among them.
回答2:
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.
回答3:
null in an angular expression is the Javascript null not as $scope.null. It's easy to check that using the expression evaluation example at https://docs.angularjs.org/guide/expression
I just tried entering 4 expressions:
null=1 =>
null =>
x=1 => 1
x => 1
and as you can see while you can set and access a variable such as x, trying to use null as a variable doesn't work in the angular expression evaluator.
回答4:
As estus says, Angular recognizes null.
If you want, you can do this in your controller: Check if the value is null (undefined will return false)
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.bar = 'notNull';
$scope.isNull = function(val) {
return val === null;
//If you want to check undefined as well, use :
//return angular.isUndefined(val) || val === null;
};
}
<div ng-controller="MyCtrl">
<span ng-show="!isNull(bar)">Hello, {{bar}}!</span>
</div>
来源:https://stackoverflow.com/questions/31387397/does-angularjs-treates-null-as-scope-null