繁体   English   中英

如何按属性值过滤ng-repeat?

[英]How to filter ng-repeat by property value?

使用ng-repeat迭代列表时,如何通过这些项目的属性添加条件/过滤器。

示例(在现实世界中当然有几个项目):

{"items":[{"type":"xxx"}]}

我只想显示type!='test'

以下内容仅显示任何内容:

<ul ng-repeat="item in items | filter: (item.type != 'test')">

如果我卸下过滤器,则所有项目都会被打印出来。

另外,如果可能,我如何创建一个条件来检查不允许的多个 type值?

您可以将ng-repeat更改如下:

<ul ng-repeat="item in items | filter: {type: '!test'}">

为了提供多个type值,您可以创建自己的过滤器以实现可重用性,如下所示:

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;
    });
  }
});

然后将您的ng-repeat语句更改为:

//List array of criteria...
<ul ng-repeat="item in items | typeFilter:['test'] ">

很简单,在过滤器表达式中使用一个函数。

 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> 

如果您的数据模式更改,只需更新过滤器功能。

您也可以使用对象符号

 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> 

但这有一些局限性,例如不支持原始值过滤器(它希望对象具有属性作为项目),并且不能多次指定同一过滤器(类似{type:"!test!xxx"}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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