Why am I getting different results from ng-show=“!emptyArray” and ng-hide=“emptyArray”?

前端 未结 3 450
深忆病人
深忆病人 2020-12-30 00:53

I have always thought ngShow and ngHide act as boolean counterpart to each other. That belief, however, is shaken by the unexpected behaviour of

相关标签:
3条回答
  • 2020-12-30 01:12

    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.

    0 讨论(0)
  • 2020-12-30 01:17

    I use something like this , it works to me

    ng-hide="array.length == 0"
    
    0 讨论(0)
  • 2020-12-30 01:26

    ng-if and ng-show mistreats "[]" (empty array)

    See: this link

    [] == true
    false
    
     [] != true
     true
    
    (![]) == true
    false
    
    [''] == true
    false
    
    (!['']) == true
    false
    
    "" == true
    false
    
    "[]" == true
    false
    
    (!"[]") == true
    false
    

    Sounds its by design.

    0 讨论(0)
提交回复
热议问题