Angularjs Use Filter On Search Bar for an Array List of Items

Saturday, 31 December 2016

This article helps you to create a search bar using angularjs and search items from the list of array items.

First open your app.js file and create a list of array items. According to given below example.

angular.module('myapp', [])
.controller("myCtrl",function($scope){

 $scope.items=[
 {
  name: "Amit",
  address:"Delhi",
  id:1235
 },
 {
  name: "Yovraj",
  address:"Mumbai",
  id:65445
 },

 {
  name: "Mukesh",
  address:"Delhi",
  id:45312
 }];

})

Now create a custom filter if you want to search by using name, address or id.
Use below example to create your custom filter.


.filter('searchFor', function(){
 // All filters must return a function. The first parameter
 // is the data that is to be filtered, and the second is an
 // argument that may be passed with a colon (searchFor:searchString)

    return function(arr, searchString){
        if(!searchString){
            return arr;
        }
        var result = [];

       searchString = searchString.toLowerCase();
// Using the forEach helper method to loop through the array
        angular.forEach(arr, function(item){
       var searchitems=item.name+" "+item.address+" "+item.id; 
           if(searchitems.toLowerCase().indexOf(searchString)){
         result.push(item);
         }
         });
    
   return result; 
}
})

Now on html page create a search bar and show all the list of array items.


<div>
<p>Search:</p>
<input type="text" ng-model="searchString">
</div>

<div ng-repeat=i in items| searchFor:searchString>
{{i.name}}<br>
{{i.address}}<br>>
{{i.id}}
</div>

Follow all the instruction carefully if facing any problem comment below.
Thank You.


1 comment

  1. I'd be trampled if all sites gave articles like these awesome articles.
    tutorial for c++

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...
Related Posts Plugin for WordPress, Blogger...
 

Most Reading

Labels