使用角度滤波器搜索

时间:2015-07-13 10:20:45

标签: angularjs angularjs-filter

参考下面的代码。

使用角度过滤器我可以搜索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 个答案:

答案 0 :(得分:1)

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

超级简单的例子

private void Form1_ResizeBegin(object sender, EventArgs e)
{
    tableLayoutPanel1.SuspendLayout();
}

private void Form1_ResizeEnd(object sender, EventArgs e)
{
    tableLayoutPanel1.ResumeLayout();
}

HTML

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

答案 1 :(得分: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">

你不需要使用&#39; - &#39;在你的搜索中,只需使用&#34; Mary 800&#34;或者&#34; Adam 555&#34;