AngularJS使用单个字段过滤多个(但不是全部)值

时间:2015-05-28 12:12:38

标签: angularjs

如何使用多个值过滤单个字段的angularJS对象? 可以说对象包含person.id person.firstName person.LastName person.birthday 我想要的是让一个搜索字段按person.firstNameperson.lastNameperson.id进行过滤,但不要按person.birthday进行过滤 我该如何实现?

2 个答案:

答案 0 :(得分:1)

您通常会为此创建自己的过滤器:

Plunker Demo

<强> MARKUP:

<body ng-controller="MainCtrl">
  <label>Search:
    <input ng-model="searchString" />
  </label>
  <div ng-repeat="person in persons | byFullName: searchString ">{{person.id}}. {{person.LastName}}, {{person.firstName}}: {{person.birthday}}</div>
</body>

<强> JS:

var app = angular.module('filter.demo', []);
app.controller('MainCtrl', ['$scope', function($scope){
  $scope.persons = [
    {id: 1, firstName: 'John', LastName: 'Doe', birthday: '01/02/2000'},
    {id: 2, firstName: 'Jane', LastName: 'Smith', birthday: '03/02/2001'},
    {id: 3, firstName: 'Mark', LastName: 'Johnson', birthday: '01/25/2001'},
    {id: 4, firstName: 'Karen', LastName: 'Smith', birthday: '04/02/2000'},
    {id: 5, firstName: 'John', LastName: 'Marker', birthday: '01/18/2003'}
  ];
}]);
app.filter('byFullName', function() {
  return function(names, search) { 
      //names is the array that is passed to the filter 
      //search is the comparison value passed to the filter 
      if(angular.isDefined(search)) {
      //make sure search is not undefined
      var results = [];
      var i;
      var searchVal = search.toLowerCase();
      for(i = 0; i < names.length; i++){
        var firstName = names[i].firstName.toLowerCase();
        var lastName = names[i].LastName.toLowerCase();
        //*OPTIONAL: convert values to lowercase for case insensitive filter
        if(firstName.indexOf(searchVal) >=0 || lastName.indexOf(searchVal) >=0){
        //Loop over the array and check if the search string matches either
        //the firstName or LastName
          results.push(names[i]);
          //If there's a match, add the value to the results array that is returned
        }
      }
      return results;
    } else {
      return names;
      //If no search value is provided, we just want to return the whole array
    }
  };
});

答案 1 :(得分:0)

如果需要,您可以链接过滤器。例如:

 <receiver android:name="yourmainpackagename.CognalysVerification" >
    <intent-filter>
        <action android:name="com.matesnetwork.cognalys" />
    </intent-filter>
</receiver>