January 21, 2016

AngularJS Filter - How to limit filter on array of items to match with desired field.

AngularJS default filter enables us to filter items list according to a specified input text. By definition, It selects a subset of items from array and returns it as a new array.
For example we have the following list of users:
$scope.myList = [
{
  firstName: "Muhammad",
  lastName: "Idrees",
  description: "Idrees is working as Senior .Net Developer, connected with Ehsan and Faizan"
}, 
{
  firstName: "Ehsan",
  lastName: "Sajjad",
  description: "Ehsan is working as Senior .Net Developer, connected with Idrees"
},
{
  firstName: "Faizan",
  lastName: "Ahmed",
  description: "Faizan is technical consultant, connected with Idrees"
}
]
And here is our html markup, how we want to filter on this list:
 <body ng-app="demoApp" ng-controller="MyController" >
     <p >
        Search:
         <input type="text" ng-model="searchInput" / >
     </p >
     <p >
         <ul>
             <li ng-repeat="user in myList | filter: searchInput">
                 <h4 >{{user.firstName}} {{user.lastName}} </h4 >
                 <p >{{user.description}} </p >
             </li >
         </ul >
     </p >
 </body >
Now if we search for the name Ehsan by typing in the input field, it will display first two items, because both objects containing this search term (in firstname, lastname, or description).
But if I want to filter my list only for firstName, and do not want to match for lastName and description fields. This is how I can limit my filter to desired field.
 <ul>
   <li ng-repeat="user in myList | filter: { firstName : searchInput}" >
    <h4 >{{user.firstName}} {{user.lastName}} </h4 >
    <p >{{user.description}} </p >
   </li >
  </ul >
Now if we type any search term it will only look for that filter in the firstName field. If any record matches the term, it will be displayed.

2 comments:


  1. First is to thank you for all this informative posts you give us for free; i bet all of us are happy.
    Such a great idea of yours! You have been a big help for me. Thanks a lot. more post for interesting topic. Great!

    SAP training in Chennai

    ReplyDelete