使用Angular过滤器进行搜索

3

请参考以下代码。

使用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链接:http://plnkr.co/edit/p7valhnDulHorw8xDYu8?p=preview

2个回答

1
这是 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>

谢谢您的回答。我明白我需要编写一个自定义过滤器来实现我的要求,但您确定不能使用默认过滤器吗? - Ashish Mishra
不,这是不可能的。您想根据2个属性进行搜索,但过滤器只有单个参数。您必须解析过滤器值,才能够按照2个不同的值在2个不同的属性中进行搜索。 - David Votrubec

0

我认为这会做你想要的事情。

更改重复:

<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”


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接