Igor Simic
8 years ago

How to put a delay on AngularJS instant search?

The issue here is that the search will execute every time the model changes, which is every keyup action on an input.

There would be cleaner ways to do this, but probably the easiest way would be to switch the binding so that you have a $scope property defined inside your Controller on which your filter operates. That way you can control how frequently that $scope variable is updated. Something like this:


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

App.controller('DisplayController', function($scope, $http, $timeout) {
        $scope.entries = result.data;

    // This is what you will bind the filter to
    $scope.filterText = '';

    // Instantiate these variables outside the watch
    var tempFilterText = '',
    $scope.$watch('searchText', function (val) {
        if (filterTextTimeout) $timeout.cancel(filterTextTimeout);

        tempFilterText = val;
        filterTextTimeout = $timeout(function() {
            $scope.filterText = tempFilterText;
        }, 250); // delay 250 ms


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