Search using angular filter

See below code.

Using angular filter I can search for friend.name or friend.phone or both, but how do I search in a string that concatenates both like in the code example below, I want to search for "mary - 80" and should only display one item list "Mary - 800-BIG-MARY".

How to do it, pls help me. Is it possible to use the default angularjs filter?

<!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 for the same code: http://plnkr.co/edit/p7valhnDulHorw8xDYu8?p=preview

+3


source to share


2 answers


How angularJs default filter works. If you want to filter by a specific combination of properties, you need to implement your own filtering function. Like here https://scotch.io/tutorials/building-custom-angularjs-filters

super simple example

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

      



Html

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

      

+1


source


I think this will do what you want

change repetition:

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

      

and then add this filter



  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;
    }
  });

      

don't forget to add ng-app

<body ng-app="myApp">

      

you don't need to use "-" in your search, just use "Mary 800" or "Adam 555"

0


source







All Articles