
The below example implements a search in which the search String is compared with the Array list. It uses indexOf method to compare the search string with the items. The attribute ng-repeat is used to print the list of items in the li tag.
AngularJS Filter Code:
.filter('mySearch', function(){ return function(ary, str){ if(!str){ return ary; } var result = []; str = str.toLowerCase(); angular.forEach(ary, function(item){ if(item.title.toLowerCase().indexOf(str) !== -1){ result.push(item); } }); return result; }; })
Demo:
-
{{item.title}}
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>AngularJS Search with custom filter</title> </head> <body ng-app="myAppSearch" ng-controller="SearchController"> <div class="search"> <span><strong>Search : </strong><input type="text" style="box-shadow: 0 0 5px rgba(81, 203, 238, 1); padding: 3px 0px 3px 3px; margin: 5px 1px 3px 0px; border: 1px solid rgba(81, 203, 238, 1); height: 25px; width: 250px;"ng-model="str" placeholder="Search Here..." /></span> </div> <ul> <li ng-repeat="item in items | mySearch:str"> <p>{{item.title}}</p> </li> </ul> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> <script> var app = angular.module("myAppSearch", []); app.filter('mySearch', function(){ return function(ary, str){ if(!str){ return ary; } var result = []; str = str.toLowerCase(); angular.forEach(ary, function(item){ if(item.title.toLowerCase().indexOf(str) !== -1){ result.push(item); } }); return result; }; }) .controller('SearchController', function($scope) { $scope.items = [ { title: 'Code Expertz', }, { title: 'AngularJS ', }, { title: 'Drupal', }, { title: 'Java Script', }, { title: 'NodeJS', }, { title: 'Cron Tab Generator', }, { title: 'Password Generator', }, { title: 'Ionic', } ]; }); </script> </body> </html>