使用 angular 过滤器搜索

searching using angular filter

参考下面的代码。

使用 angular 过滤器我可以搜索 friend.name 或 friend.phone 或两者,但是如何在结合了两者的字符串中进行搜索,就像下面的示例代码一样,我想进行搜索对于 "mary - 80" 并且它应该只显示一个列表元素 "Mary - 800-BIG-MARY".

这个怎么弄,请帮帮我。 是否可以使用默认 angularjs 过滤器?

<!doctype html>
    <head>
       <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script> 
    </head>

<body ng-app="">
    <div ng-init="friends = [{name:'John', phone:'555-1276'},
                     {name:'Mary', phone:'800-BIG-MARY'},
                     {name:'Mike', phone:'555-4321'},
                     {name:'Adam', phone:'555-5678'},
                     {name:'Julie', phone:'555-8765'},
                     {name:'Juliette', phone:'555-5678'}]"></div>

    <label>Search: <input ng-model="searchText"></label>
    <li ng-repeat="friend in friends | filter: searchText">
        <span>{{friend.name}} - {{friend.phone}}</span>
    </li>
</body>
</html>

plunker link 相同代码:http://plnkr.co/edit/p7valhnDulHorw8xDYu8?p=preview

默认情况下 angularJs 过滤器就是这样工作的。如果要按特定的属性组合进行过滤,则必须实现自己的过滤功能。 喜欢这里https://scotch.io/tutorials/building-custom-angularjs-filters

超级简单的例子

  $scope.customFilter = (item)=> {
    //TODO: Add your own properties here
    return item.someProperty == $scope.filterValue;
  };

html

<htmlElement ng-repeat="item in itemList | filter:customFilter"></htmlElement>

我认为这会满足您的要求

更改重复:

<li ng-repeat="friend in friends | filterText:searchText">

然后添加这个过滤器

  app= angular.module("myApp",[]);

  app.filter("filterText",function(){
    return function(items,text){
      var result = [];
      text = text != undefined ? text : "";

      var words = text.split(" ");

      angular.forEach(items,function(v,i){

          allFound = true;
          angular.forEach(words,function(v2,i2){
             if((v.name+v.phone).toUpperCase().indexOf(v2.toUpperCase())==-1){
                allFound = false;
             }
          })
          if(allFound)
          result.push(v);

      });
       return result;
    }
  });

记得添加 ng-app

<body ng-app="myApp">

您不需要在搜索中使用“-”,只需使用 "Mary 800" 或 "Adam 555"