How to put a delay on AngularJS instant search?

braincomb picture braincomb · Mar 8, 2013 · Viewed 138.7k times · Source

I have a performance issue that I can't seem to address. I have an instant search but it's somewhat laggy, since it starts searching on each keyup().

JS:

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

App.controller('DisplayController', function($scope, $http) {
$http.get('data.json').then(function(result){
    $scope.entries = result.data;
});
});

HTML:

<input id="searchText" type="search" placeholder="live search..." ng-model="searchText" />
<div class="entry" ng-repeat="entry in entries | filter:searchText">
<span>{{entry.content}}</span>
</div>

The JSON data isn't even that large, 300KB only, I think what I need to accomplish is to put a delay of ~1 sec on the search to wait for the user to finish typing, instead of performing the action on each keystroke. AngularJS does this internally, and after reading docs and other topics on here I couldn't find a specific answer.

I would appreciate any pointers on how I can delay the instant search.

Answer

Josue Alexander Ibarra picture Josue Alexander Ibarra · Aug 28, 2013

UPDATE

Now it's easier than ever (Angular 1.3), just add a debounce option on the model.

<input type="text" ng-model="searchStr" ng-model-options="{debounce: 1000}">

Updated plunker:
http://plnkr.co/edit/4V13gK

Documentation on ngModelOptions:
https://docs.angularjs.org/api/ng/directive/ngModelOptions

Old method:

Here's another method with no dependencies beyond angular itself.

You need set a timeout and compare your current string with the past version, if both are the same then it performs the search.

$scope.$watch('searchStr', function (tmpStr)
{
  if (!tmpStr || tmpStr.length == 0)
    return 0;
   $timeout(function() {

    // if searchStr is still the same..
    // go ahead and retrieve the data
    if (tmpStr === $scope.searchStr)
    {
      $http.get('//echo.jsontest.com/res/'+ tmpStr).success(function(data) {
        // update the textarea
        $scope.responseData = data.res; 
      });
    }
  }, 1000);
});

and this goes into your view:

<input type="text" data-ng-model="searchStr">

<textarea> {{responseData}} </textarea>

The mandatory plunker: http://plnkr.co/dAPmwf