5

这似乎一定很简单,我只是找不到答案。

假设我有一个数据数组,如下所示:

friends = [{name:'John', age:60, location:'Brighton', street:'Middle Street'},
{name:'Bob', age:5, location:'Brighton', street:'High Street'}];

现在,我想根据文本输入过滤数据,如下所示:

<input ng-model="searchText">
<ul>
    <li ng-repeat="friend in friends | orderBy:'name' | filter:searchText">
    {{friend.name}} - {{friend.location}}</li>
</ul>

这很好用,但它会根据朋友对象的每个属性(姓名、年龄、位置和街道)过滤输入文本。我希望能够仅根据名称和位置进行过滤(忽略年龄和街道)。如果没有自定义过滤器,这可能吗?

4

4 回答 4

7

是的,只需将谓词而不是字符串传递给过滤器即可:

<li ng-repeat="friend in friends | orderBy:'name' | filter:friendContainsSearchText">

$scope.friendContainsSearchText = function(friend) {
    return friend.name.indexOf($scope.searchText) >= 0 || friend.location.indexOf($scope.searchText) >= 0
}
于 2013-10-11T20:49:32.207 回答
2

这是我们使用自定义过滤器的方法。

演示http ://plnkr.co/edit/q7tYjOvFjQHSR0QyGETj?p=preview )

[array] | search:query:columns:operator

> query: this is the term you are looking for
> columns: an array of the names of the properties you want to look for (if empty, will use the angular filter with query)
> operator: a boolean to switch between OR (true) and AND (false, default)

html

<ul>
  <li ng-repeat="item in list | search:query:['name','location']:operator">
    <pre>{{item | json}}</pre>
  </li>
</ul>

js

app.filter('search', function($filter) {
  return function(input, term, fields, operator) {
    if (!term) {
       return input;
    }

    fields || (fields = []);

    if (!fields.length) {
      return $filter('filter')(input, term);
    }

    operator || (operator = false); // true=OR, false=AND

    var filtered = [], valid;

    angular.forEach(input, function(value, key) {
      valid = !operator;
      for(var i in fields) {
        var index = value[fields[i]].toLowerCase().indexOf(term.toLowerCase());
        // OR : found any? valid
        if (operator && index >= 0) { 
          valid = true; break;
        } 
        // AND: not found once? invalid 
        else if (!operator && index < 0) { 
          valid = false; break;
        }
      }
      if (valid) {
        this.push(value);
      }
    }, filtered);

    return filtered;
  };
});
于 2013-10-11T23:25:09.743 回答
1

或者,您可以使用:

<li ng-repeat="friend in friends | orderBy:'name' | filter:{ name :searchText}">

于 2013-10-11T20:55:01.770 回答
-1

您可以像...一样放置多个过滤器。

<div>
    <input ng-model="Ctrl.firstName" />
    <input ng-model="Ctrl.age" />

    <li ng-repeat = "employee in Ctrl.employees | filter:{name:Ctrl.firstName} | filter:{age:Ctrl.age}">{{employee.firstName}}</li>
</div>
于 2014-04-17T15:30:37.730 回答