为什么我从NG-节目获得不同的结果= QUOT;!emptyArray"和NG-隐藏=" emptyArray"? [英] Why am I getting different results from ng-show="!emptyArray" and ng-hide="emptyArray"?

查看:184
本文介绍了为什么我从NG-节目获得不同的结果= QUOT;!emptyArray"和NG-隐藏=" emptyArray"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直以为 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.

下面是一个演示plunker 。为什么不是 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()评估中传递的值。下面是的 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;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆