AngularJs ng-repeat Filter By Limit Conditionally

814 views Asked by At

How can I run the ng-repeat for maximum 2 times but each iteration should meet the condition and output the final data with two elements. For example, I have an array like:

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

And the HTML is this:

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

The issue is, I'm getting only 1 element as an output, i.e. Ali instead of Ali and Hammad. Because ng-repeat stopped after 2nd iteration and didn't check the other elements. So, how can I get all the matching elements by status==true with the given limit?

1

There are 1 answers

1
miqh On BEST ANSWER

You can chain filter onto your ng-repeat expression to apply the conditional filtering you need first before limitTo kicks in.

Note that the ordering of expressions is significant in this approach.

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>