Live search using custom filter in Angular Js

Live search is a powerful feature that enhances the user experience by providing real-time search results as the user types in their query. This feature is especially useful in applications that deal with large amounts of data, where traditional search methods can be slow and inefficient. In this tutorial, we will learn how to implement live search using AngularJS, a popular JavaScript framework.

Setting Up the Project

Before we start, let’s set up our project structure. We will need three main folders: css for our stylesheets, js for our JavaScript files, and a json file that contains the data we will be searching through. For the purpose of this tutorial, we will be using a temporary data.json file.

Creating the HTML File

Our main HTML file, index.html, will contain the structure of our application. We will define our AngularJS application and controller in this file using the ng-app and ng-controller directives, respectively. We will also use the ng-model directive to bind our search input box to our model.

<body ng-app="instantsearch" ng-controller="instantSearchCtrl">
  <input type="text" ng-model="searchString" placeholder="Search">
  <ul>
    <li ng-repeat="i in items | searchFor:searchString">
      {{i.title}}
    </li>
  </ul>
</body>

Creating the AngularJS Application and Controller

Next, we will create our AngularJS application and controller in our site.js file. We will use the $http service to fetch our data from the data.json file and assign it to our $scope.items object.

var app = angular.module('instantsearch',[]);

app.controller('instantSearchCtrl',function($scope,$http){
  $http.get('data.json').success(function(data, status, headers, config) {
    $scope.items = data.data;
  }).error(function(data, status, headers, config) {
    console.log("No data found..");
  });
});

Creating the Custom Filter

Finally, we will create a custom filter that will perform the live search functionality. This filter will take an array and a search string as input, and return an array of items that match the search string.

app.filter('searchFor', function(){
  return function(arr, searchString){
    if(!searchString){
      return arr;
    }
    var result = [];
    searchString = searchString.toLowerCase();
    angular.forEach(arr, function(item){
      if(item.title.toLowerCase().indexOf(searchString) !== -1){
        result.push(item);
      }
    });
    return result;
  };
});

Conclusion

And that’s it! We have successfully implemented live search using AngularJS. This feature can greatly enhance the user experience in your applications, and with AngularJS, it’s incredibly easy to implement. Happy coding!

Facebook
Twitter
LinkedIn
Pinterest

Table of Contents

Related posts