AngularJs ng有条件地重复按限制筛选



如何运行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>

问题是,我只得到一个元素作为输出,即Ali,而不是AriHammad。因为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>

最新更新