[英]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和Hammad 。 因為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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.