问题描述
我一直以为 ngShow
和 ngHide
充当布尔对口对方。这种信念,然而,是由意外的行为动摇了 ngShow
当空数组参与。
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.
下面是一个。为什么不是 NG-秀=!emptyArray
行为就像 NG-隐藏=emptyArray
?
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>
编辑:
AngularJS的指令隐藏
或显示
取决于函数 toBoolean()
评估中传递的值。下面是的:
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;
}
和您可以验证在JS控制台下面code:
And you can verify the following code in JS console:
>var emptyArray = [];
>toBoolean(emptyArray)
false
>toBoolean(!emptyArray)
false
这解释了为什么。由于当 emptyArray
传递给 toBoolean()
直接,它的计算结果正确的结果假
。然而,当!emptyArray
传递给 toBoolean()
,它不评估为真
,因为!emptyArray
是假
本身。
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.
希望它帮助。
这篇关于为什么我从NG-节目获得不同的结果= QUOT;!emptyArray&QUOT;和NG-隐藏=&QUOT; emptyArray&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!