Angularjs 过滤一个字段的两个值



我需要使用过滤器或其他过滤器,该怎么办?

<tr ng-repeat="currentCollectionItem in binding 
| filter: ({ isPending: false } || {isPending: undefined})">

解决方案

您只能使用一个条件来执行此操作:

filter:'!true'

这就是应用假属性和未定义属性的方法。

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-filter-filter-production</title>
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
</head>
<body ng-app="">
<div ng-init="binding = [{name:'John', isPending:false},
{name:'Mary', isPending:false},
{name:'Mike', isPending:undefined},
{name:'Adam'},
{name:'Julie', isPending:true},
{name:'Juliette', isPending:true}]"></div>
<table id="searchTextResults">
<tr><th>Name</th><th>isPending</th></tr>
<tr ng-repeat="currentCollectionItem in binding | filter:'!true'">
<td>{{ currentCollectionItem.name }}</td>
<td ng-show="{{currentCollectionItem.isPending !== undefined}}">{{ currentCollectionItem.isPending }}</td>
<td ng-show="{{currentCollectionItem.isPending === undefined}}">undefined</td>
</tr>
</table>
</body>
</html>

使用自定义谓词函数:

<tr ng-repeat="currentCollectionItem in binding | filter: notPendingFilterFn">
$scope.notPendingFilterFn = function(value, index, array) {
return value.isPending === false || value.isPending === undefined;
};

谓词函数可用于编写任意筛选器。为数组的每个元素调用该函数,元素、其索引和整个数组本身作为参数。

有关详细信息,请参阅

  • AngularJSfilterFilter API 参考

最好的办法是在控制器/组件类上定义一个过滤器方法,并改用该方法。

这有两个主要优点:

  1. 更易于单元测试 - 可以直接在控制器/组件实例上调用函数来测试筛选器逻辑。
  2. 更简单的标记/将复杂的代码保留在 JS 中它所属的位置。

如果您需要帮助执行此操作,请告诉我。

最新更新