Igor Simic
6 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:

JS:


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

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

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

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

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

HTML:


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


http://stackoverflow.com/questions/15304562/how-to-put-a-delay-on-angularjs-instant-search