简体   繁体   中英

AngularJs ng-repeat Filter By Limit Conditionally

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, ie 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?

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM