angularjs中的多个过滤器

时间:2016-10-18 03:04:21

标签: angularjs angularjs-filter

我是棱角分明的新人。我有一个json对象:

[
  {
    "id": 1,
    "name": "name1",
    "speciality": "speciality1",
    "address": "address1",
    "phoneNumber": 9999999999
  },
  {
    "id": 2,
    "name": "name2",
    "speciality": "speciality2",
    "address": "address2",
    "phoneNumber": 9999999999
  },
...
]

我希望根据两个属性进行过滤:namespeciality。此搜索匹配不敏感的子字符串。这该怎么做?我这样做的方式如下,但不起作用:

$filter('filter')(doctor.details, { $: query }, false, [name, speciality]);
$filter('filter')(doctor.details, { name: query } || {speciality : query }, false);

doctor.details是json对象数组,query是要与namespeciality匹配的(子)字符串。

2 个答案:

答案 0 :(得分:0)

您可以编写一个AngularJS filter来根据query匹配namespeciality属性过滤掉列表。

app.filter('filterDetails', function() {
  return function(details, query) {

    var filteredDetails = [];
    filteredDetails = details.filter(function(obj) {
      // look whether query is substring of name or speciality
      if (~obj.name.indexOf(query) || ~obj.speciality.indexOf(query)) {
        return obj;
      }
    })
    // finally return filtered array
    return filteredDetails;
  };
});

HTML

 Query :
  <input type="text" ng-model="query" />

  <ul>
    <li ng-repeat="detail in doctor.details | filterDetails:query">
      {{ detail }}
    </li>
  </ul>

Plunker

答案 1 :(得分:0)

是否使用lodash,因为这是我能想到的最简单的方法:

_.union($filter('filter')(doctor.details, { name: query }), $filter('filter')(doctor.details, { speciality: query }));