Angularjs – Correct way to program a search text box in angularJs


A very common feature in several parts of my application is a search box that accepts a string and then filters an table based on the string.

What I am aiming for is the ability to permit user to type in something and automatically after a few ms of delay the results update themselves. i.e no need to hit the enter button.

Ofcourse sorting of the data would be done using AngularJs filters. However before we update the filter I believe we first have to understand that the user has completed entering the input and is now waiting for the results.

So I mapped out the directive which will be attached to the search input box .

<input type="text"  update-filter placeholder="Enter search term">

 //and the directive goes like this
app.directive('updateFilter', [ '$timeout', function($timeout){
  var delay;
  return {
    link: function(scope, element){
         element.on('keypress', function(){
            if(!delay) {
                delay = $timeout(function() {
                  //perform the activity of updating the filter here
                 delay = undefined;

My question is, is this the right approach to take to tackle this issue or are there better solutions out there ?

Best Solution

You are overcomplicating this. It can be done much easier in angular.

<input type="text" ng-model="query" ng-model-options="{ debounce: 200 }"

Use $scope.query to access the query in your controller. Define $scope.doSearch() to do the search. The debounce option is used to wait 200ms after the user is done typing.

Related Question