角度.js. 如何计算满足自定义过滤器的 ng 重复迭代

Angular.js. How to count ng-repeat iterations which satisfy the custom filter

本文关键字:过滤器 自定义 ng 迭代 满足 js 何计算 计算 角度      更新时间:2023-09-26

这是我的代码:

<div ng-show="?" ng-repeat="item in items | notEmpty">
</div>

滤波器:

Kb.filter("notEmpty", function(){ 
  return function(input){
    var output=[];
    for(var i=0;i<input.length;i++){
      if(input[i]){
        output.push(input[i]);
      }
    }
    return output;
}});

我需要根据循环中过滤项目的数量显示/隐藏重复的s。最好的方法是什么?

谢谢

ng-repeat表达式允许将过滤结果分配给变量。可以从当前范围访问此变量,因此您可以根据需要在同一范围内使用它:

<p>Number of filtered items: {{filteredItems.length}}</p>
<div 
  ng-show="filteredItems.length > 0" 
  ng-repeat="item in filteredItems = (items | notEmpty)"
>
 {{$index}}
</div>

最简单的方法可能是在控制器中运行筛选器。像这样:

function MyCtrl($scope, notEmptyFilter)
{
    //$scope.items is put into the scope somehow
    $scope.filteredItems = notEmptyFilter($scope.items);
}

那么你的 HTML 将看起来像这样:

<div ng-show="filteredItems.length > 0" ng-repeat="item in filteredItems">
</div>

从 Angular 1.3 开始,您可以使用以下语法进行ng-repeat

variable in expression as alias_expression

那是:

<p>Number of filtered items: {{filteredItems.length}}</p>
<div ng-repeat="item in items | notEmpty as filteredItems">
 ...
</div>

我找到了这个

如何显示过滤后的ng重复数据的长度,

描述在筛选列表后获取计数