Search code examples
javascriptangularjstimeoutdelay

How to trigger $watch after 2s delay or execute the last condition of a subscribed property of a scope?


I have a search input which triggers watch and then send a new request to DB

var timeoutPromise;
var delayInMs = 2000;
$scope.$watch('search', function() {
    $timeout.cancel(timeoutPromise); 
    timeoutPromise = $timeout(function(){ 
        $scope.nameFilter = '&filter[]=Name,cs,' + $scope.search;
        $scope.updatePage(1);
    });
}, delayInMs);

The main goal of the delay was triggering watch not on each new character in the search input but after amending at least several letters.

Unfortunately, this watch just put all requests in a queue and executes all request after the delay.

Please help me


Solution

  • Angular comes with things like this built in, just in a slightly different way. I would suggest doing it like this, the part which delays the change is in the ng-model-options

    JS

    $scope.search = "";
    
    $scope.searchFunction = function(){ 
        $scope.nameFilter = '&filter[]=Name,cs,' + $scope.search;
        $scope.updatePage(1);
    }
    

    HTML

    <input type="text" ng-model="search" ng-change="searchFunction()" ng-model-options="{ debounce: 2000 }" />
    

    You may also want to take advantage of the input type search