2016-08-23 35 views
1

可见的元素,我想知道的是受一个NG-如果NG-显示后显示可见元件的数量。这里是一个简化的例子:计数的NG-重复

$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> 

有没有一种方法来计算结果显示的项目数?

+0

你是指结果项目的数量? –

+0

是的。感谢您的期待,但我能弄明白:) – sleepycow

回答

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; 
    } 
} 
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>

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