【问题标题】:Checking size of an array检查数组的大小
【发布时间】:2014-10-10 13:23:37
【问题描述】:

我有一个总是返回 20 项的数组。但是,如果返回的项目少于 20 个,则返回一个 " " 而不是减少数组中的数量。

例如,myArray 有 20 个项目(只有 15 个值)。

$scope.myArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", " ", " ", " ", " ", " "]

我想根据 myArray 中填充的项目数对某些元素执行 ng-show/hide/if。

最初我尝试过:

<div ng-show="myArray.length > 10">
    Show if more than 10 items
</div>

<div ng-show="myArray.length > 15">
    Show if more than 15 items
</div>

<div ng-show="myArray.length > 19">
    Show if more than 19 items
</div>

当然,以上所有内容都会显示,因为总是返回 20 项。

我可以通过 ng-show/hide/if 来实现这一点,而不必在我的控制器中编写额外的 JS 吗?

【问题讨论】:

    标签: angularjs angularjs-scope ng-show angular-ng-if ng-hide


    【解决方案1】:

    只过滤掉空白项:

    var outBlanks = Boolean;
    
    $scope.nonBlanksCount = $scope.myArray.filter(outBlanks).length;
    
    <div ng-show="nonBlanksCount > 10">
        Show if more than 10 items
    </div>
    

    我刚刚读到您不想向控制器添加任何逻辑。在这种情况下,您可以编写一个自定义过滤器(例如filterBlanks),它执行与上述相同的操作并执行以下操作:

    <div ng-show="(myArray | filterBlanks).length > 10">
        Show if more than 10 items
    </div>
    

    但是在这种情况下,过滤器会被执行多次,效率不高。

    【讨论】:

    • 我喜欢你的第二个解决方案。filterBlanks 会是什么样子?
    【解决方案2】:

    如果你像这样简单地扩充你的数组,它对你有用吗?

    $scope.myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, "", "", "", ""].filter(Boolean);
    

    【讨论】:

    • 因为你的答案偷了我的想法,我偷了你的一部分;)使用Boolean 肯定更优雅。
    • 哦,当然,我只是想改进你的,因为他想在作用域上写很少或不写 js,但原生函数不能用于这样的绑定,所以他必须这样做。所以几乎是我试图缩短你的唯一解决方案
    猜你喜欢
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    • 2017-07-09
    • 2019-06-11
    • 1970-01-01
    相关资源
    最近更新 更多