AngularJS watch: $ debut

I have the following html that represents a search box:

<input ng-model-options="{ debounce: 500 }" type="text" ng-model="name">

And the following js:

$scope.$watch('name', function(newVal, oldVal) {
            if(newVal != oldVal) {
                $scope.pageChanged($scope.sort, $scope.name, $scope.sortDirection);
            }
        });

Now my pageChanged function makes a REST call on my server and returns a list of addresses based on sorting and search information ("name"). Say my user wants to find Tom. I would like my application not to make three rest calls (name = "T", name = "To", name = "Tom").

I tried to do this using debounce, but it seems like the clock is not working with debounce, so I was wondering what would be the best way to implement this with minimal code?

+4
source share
2 answers

ng-change , .

<input ng-model-options="{ debounce: 500 }" type="text" ng-model="name" ng-change="modelChanged()">

JS:

var timeout = $timeout(function(){});

$scope.modelChanged = function(){
    $timeout.cancel(timeout); //cancel the last timeout
    timeout = $timeout(function(){
        $scope.pageChanged($scope.sort, $scope.name, $scope.sortDirection);
    }, 500);
};

debounce, .

+4

!

:

, debounce , lodash ( (@Pete BD answer).

// Create an AngularJS service called debounce
app.factory('debounce', ['$timeout','$q', function($timeout, $q) {
  // The service is actually this function, which we call with the func
  // that should be debounced and how long to wait in between calls
  return function debounce(func, wait, immediate) {
    var timeout;
    // Create a deferred object that will be resolved when we need to
    // actually call the func
    var deferred = $q.defer();
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        if(!immediate) {
          deferred.resolve(func.apply(context, args));
          deferred = $q.defer();
        }
      };
      var callNow = immediate && !timeout;
      if ( timeout ) {
        $timeout.cancel(timeout);
      }
      timeout = $timeout(later, wait);
      if (callNow) {
        deferred.resolve(func.apply(context,args));
        deferred = $q.defer();
      }
      return deferred.promise;
    };
  };
}]);

/, $watch, ( ):

$scope.$watch('name', debounce(function(newVal, oldVal) {
   if(newVal != oldVal) {
     $scope.pageChanged($scope.sort, $scope.name, $scope.sortDirection);
   }
}, 500));

!


:

:

$scope.$watch('name', function(newVal, oldVal) {

   debounce(function() {
     if(newVal != oldVal) {
       $scope.pageChanged($scope.sort, $scope.name, $scope.sortDirection);
     },500)();
});

, 50 .

0

Source: https://habr.com/ru/post/1583746/


All Articles