Implement a delay on $scope.$watch

前端 未结 5 1613
醉话见心
醉话见心 2021-02-07 03:33

I was wondering whether or not it is possible to implement a slight delay on $scope.$watch. I have the following which queries the server, so I\'d like to implement a slight del

5条回答
  •  一生所求
    2021-02-07 03:59

    Just a snippet that I found useful for similar case:

    function watchWithDelay(scope, prop, callback, delayMs) {
      delayMs = delayMs || 1000;
      var lastTimeChanged = new Date();
      scope.$watch(prop, function(n, o) {
        lastTimeChanged = new Date();
        setTimeout(function() {
          var diff = new Date().getTime() - lastTimeChanged.getTime();
          if (diff < delayMs-100 || diff > delayMs+100) {
            return;
          }
          callback(n, o);
        }, delayMs);
      });
    }
    

    You can use it in a controller like this:

    watchWithDelay($scope, 'client.phone', function(n, o) {
      if (n === o) {
        return;
      }
      // any custom validations, for example
      if (!n) {
        return alert('Phone is required');
      }
      if (n.length < 11) {
        return alert('Phone is shorter than 11 digits');
      }
      // here I should save it somehow
      console.log('Phone is changed to ' + n);
    });
    

提交回复
热议问题