When iterating a list with ng-repeat
, how can I add a condition/filter by a property of those items.
Example (of course there are several items in real world):
{"items":[{"type":"xxx"}]}
I only want to show the item where type!='test'
.
The following just prints nothing:
<ul ng-repeat="item in items | filter: (item.type != 'test')">
Whereas if I remove the filter, all items are printed, of course.
Also, if possible, how could I create a condition that checks for multiple type
values not being permitted?
You could change your ng-repeat
to read like this:
<ul ng-repeat="item in items | filter: {type: '!test'}">
In order to provide multiple type
values you can create your own filter for reusability like so:
app.filter('typeFilter', function(){
return function(arr,criteria){
if(!angular.isDefined(criteria) || criteria == ''){
return arr;
}
return arr.filter(function(curr){
return criteria.indexOf(curr.type) == -1;
});
}
});
and then change your ng-repeat
statement to read:
//List array of criteria...
<ul ng-repeat="item in items | typeFilter:['test'] ">
Simple, use a function in the filter expression.
angular.module('app', []) .controller('AppCtrl', function($scope) { $scope.items = [{ "type": "xxx" }, { "type": "test" }]; $scope.filterFn = function(value) { return value.type !== 'test'; }; })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="AppCtrl"> <ul> <li ng-repeat="item in items | filter: filterFn">{{item.type}}</li> </ul> </div>
If your data schema changes just update the filter function.
You could also use object notation
angular.module('app', []) .controller('AppCtrl', function($scope) { $scope.items = [{ "type": "xxx" }, { "type": "test" }]; })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="AppCtrl"> <ul> <li ng-repeat="item in items | filter: {type: '!test'}">{{item.type}}</li> </ul> </div>
but this has some limitations like not suporting primitive value filters(it expects an object with properties as the item) and the same filter cannot be specified multiple times(something like {type:"!test!xxx"}
)
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.