为什么我从 ng-show="!emptyArray" 得到不同的结果?和 ng-hide="emptyArray"? [英] Why am I getting different results from ng-show="!emptyArray" and ng-hide="emptyArray"?

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

问题描述

我一直认为 ngShowngHide 是彼此对应的布尔值.然而,当涉及空数组时,ngShow 的意外行为动摇了这种信念.

这是一个演示工具.为什么 ng-show="!emptyArray" 的行为不像 ng-hide="emptyArray"?

解决方案

因为[] !== false.您可以使用 !! 将长度值强制为 boolean.

emptyArray 是假的,所以不要隐藏它.</div><div ng-show="!!!emptyArray.length">!emptyArray 是真的,所以显示这个.</div>

AngularJS 的指令 hideshow 依赖于函数 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,因为 !emptyArrayfalse 本身.

希望有帮助.

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屋!

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