AngularJs ng-repeat 有条件地按限制过滤

AngularJs ng-repeat Filter By Limit Conditionally

我怎么能运行 ng-repeat最多2次,但每次迭代都应该满足condition并输出包含两个元素的最终数据。例如,我有一个像这样的数组:

$scope.users = [
    {
        id: '1',
        name:'Ali',
        status: true
    },
    {
        id: '2',
        name:'Wajahat',
        status: false
    },
    {
        id: '3',
        name:'Hammad',
        status: true
    },
    {
        id: '4',
        name:'Ahmad',
        status: true
    }
];

HTML 是这样的:

<div ng-repeat="user in users | limitTo:2" ng-if="user.status==true">{{user.name}}</div>

问题是,我只得到 1 个元素作为输出,即 Ali 而不是 Ali哈马德。因为 ng-repeat 在第二次迭代后停止并且没有检查其他元素。那么,如何在给定的限制下通过 status==true 获取所有匹配元素?

您可以将 filter 链接到您的 ng-repeat 表达式,以在 limitTo 开始之前应用您首先需要的条件过滤。

请注意,表达式的顺序在此方法中很重要。

angular
  .module('app', [])
  .controller('ctrl', function ($scope) {
    $scope.users = [
      {
        id: '1',
        name:'Ali',
        status: true,
      },
      {
        id: '2',
        name:'Wajahat',
        status: false,
      },
      {
        id: '3',
        name:'Hammad',
        status: true,
      },
      {
        id: '4',
        name:'Ahmad',
        status: true,
      }
    ];
    
  });
<div ng-app="app" ng-controller="ctrl">
  <div ng-repeat="user in users | filter:{status: true} | limitTo:2">{{ user.name }}</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>