为什么我从 ng-show="!emptyArray" 得到不同的结果?和 ng-hide="emptyArray"? [英] Why am I getting different results from ng-show="!emptyArray" and ng-hide="emptyArray"?
问题描述
我一直认为 ngShow
和 ngHide
是彼此对应的布尔值.然而,当涉及空数组时,ngShow
的意外行为动摇了这种信念.
这是一个演示工具.为什么 ng-show="!emptyArray"
的行为不像 ng-hide="emptyArray"
?
因为[] !== false
.您可以使用 !!
将长度值强制为 boolean
.
emptyArray 是假的,所以不要隐藏它.</div><div ng-show="!!!emptyArray.length">!emptyArray 是真的,所以显示这个.</div>已
AngularJS 的指令 hide
或 show
依赖于函数 toBoolean()
来评估传入的值.这里是 toBoolean()
的源代码a href="https://github.com/angular/angular.js/blob/master/src/Angular.js#L835">toBoolean():
function toBoolean(value) {if (value && value.length !== 0) {var v =小写("+值);value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');} 别的 {值 = 假;}返回值;}
并且可以在JS控制台验证如下代码:
>var emptyArray = [];>toBoolean(emptyArray)错误的>toBoolean(!emptyArray)错误的
这就解释了原因.由于当 emptyArray
直接传递给 toBoolean()
时,它会评估正确的结果 false
.但是,当 !emptyArray
传递给 toBoolean()
时,它不会计算为 true
,因为 !emptyArray
是false
本身.
希望有帮助.
I have always thought ngShow
and ngHide
act as boolean counterpart to each other. That belief, however, is shaken by the unexpected behaviour of ngShow
when an empty array is involved.
Here is a demo plunker. Why isn't ng-show="!emptyArray"
behaving like ng-hide="emptyArray"
?
解决方案 Because [] !== false
. You can coerce the length value to boolean
instead with !!
.
<div ng-hide="!!emptyArray.length">emptyArray is falsy, so do not hide this.</div>
<div ng-show="!!!emptyArray.length">!emptyArray is truthy, so show this.</div>
Edited:
AngularJS's directive hide
or show
depends on the function toBoolean()
for evaluating the value passed in. Here is the source code of toBoolean():
function toBoolean(value) {
if (value && value.length !== 0) {
var v = lowercase("" + value);
value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
} else {
value = false;
}
return value;
}
And you can verify the following code in JS console:
>var emptyArray = [];
>toBoolean(emptyArray)
false
>toBoolean(!emptyArray)
false
That explains why. Since when emptyArray
is passed to the toBoolean()
directly, it evaluates the correct result false
. However when !emptyArray
is passed to toBoolean()
, it doesn't evaluate to true
since !emptyArray
is false
itself.
Hope it helps.
这篇关于为什么我从 ng-show="!emptyArray" 得到不同的结果?和 ng-hide="emptyArray"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文