计算ng-repeat中的可见元素

时间:2016-08-23 03:19:10

标签: angularjs angularjs-ng-repeat ng-show

我想知道受 ng-if ng-show 约束后显示的可见元素的数量。这是一个简化的例子:

$scope.fruits = [
        { name: 'apple', shape: 'round', color: 'red' },
        { name: 'stop sign', shape: 'pointy', color: 'red' },
        { name: 'orange', shape: 'round', color: 'orange' },
        { name: 'tomato', shape: 'round', color: 'red'}
    ];




    <ul>
       <li ng-repeat="fruit in fruits" ng-if="fruit.color=='red'" ng-show="fruit.shape=='round'">{{fruit.name}}</li>
    </ul>

有没有办法计算结果显示的项目数?

4 个答案:

答案 0 :(得分:1)

我最终根本没有使用ng-if或ng-show,只是过滤了ng-repeat。这样,我不必隐藏任何东西,并且很容易得到结果的长度。

<ul>
   <li ng-repeat="fruit in fruits | filter:myFilter | filter:{shape:'round'} as filteredFruits">{{fruit.name}}</li>
   {{filteredFruits.length}} fruits
</ul>

$scope.myFilter = function(x) {
    if (x.color == 'red') {
        return x;
    }
}

答案 1 :(得分:0)

使用此功能,您可以移除自定义过滤器,并使用as关键字获取li长度。

var app = angular.module('myApp', []);
app.controller('Ctrl', function($scope) {
   $scope.fruits = [
        { name: 'apple', shape: 'round', color: 'red' },
        { name: 'stop sign', shape: 'pointy', color: 'red' },
        { name: 'orange', shape: 'round', color: 'orange' },
        { name: 'tomato', shape: 'round', color: 'red'}
    ];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="Ctrl">

<ul>
        <li ng-repeat="fruit in fruits| filter:{'shape':'round', 'color':'red'}" >{{fruit.name}}</li>
</ul>

</div>

答案 2 :(得分:0)

试试这个

<ul>
   <li ng-repeat="fruit in fruits | notEmpty as Items" ng-if="fruit.color=='red'" ng-show="fruit.shape=='round'">{{fruit.name}}</li>
</ul>

<p>Number of Items: {{Items.length}}</p>

答案 3 :(得分:0)

您可以计算项目数量,

$scope.fruits = [
            { name: 'apple', shape: 'round', color: 'red' },
            { name: 'stop sign', shape: 'pointy', color: 'red' },
            { name: 'orange', shape: 'round', color: 'orange' },
            { name: 'tomato', shape: 'round', color: 'red' }
        ];

        $scope.FindVisible = function () {
            var visibleObject=0;
            $scope.fruits.forEach(function (v, k) {                
                if (v.shape == 'round' && v.color == 'red') {
                    visibleObject = visibleObject + 1;                    
                }
            });
            alert(visibleObject);
        }
<ul>
        <li ng-repeat="fruit in fruits" ng-if="fruit.color=='red'" ng-show="fruit.shape=='round'">{{fruit.name}}</li>
        <button ng-click="FindVisible()">Find</button>
</ul>