0

Let's assume I have some inputs with their ng-models

<input type="text" ng-model="vm.man.name">
<input type="text" ng-model="vm.man.surName">

In my controller I have object vm.man={};. I want to do the following: I want to put $watch on my vm.man, so if I press some key inside my <input>, it should wait 3 seconds and then send response to the server. However, if I pressed some key, and during 3 seconds I pressed another key it should wait 3 seconds and then respond to the server. Here is what I have already done:

 $scope.$watch(()=>vm.man, function (newVal, oldVal) {
     if(angular.isUndefined(newVal)) {
         return console.log("newVal is Undefined")
     }else{
        vm.timer1= $timeout(function () {
         vm.someFunctionThatRespondsToServer();
         }, 3000);
     }
 }, true);

The problem I have now, it creates response per keypress. for example I pressed a in my input it responds a, then I pressed b it responds ab and etc. I want to get something like this: I pressed a it waits 3 seconds if there is no other keypresses, it responds, or I pressed a and then after 2 seconds, lets say I pressed b it waits 3 seconds and then responds ab if there were no other keypresses during 3seconds. Thanks in advance.

Dr. Abbos
  • 139
  • 2
  • 9

2 Answers2

1

In Angular 1/2 you can use function from Lodash debounce. Here is link and example: https://lodash.com/docs/4.17.4#debounce

In Angular 2 RC5 and newer you can use debounceTime. More details here Angular and debounce

hsd
  • 452
  • 5
  • 12
0

There is built in functionality for that. You want to add a debounce to the input that your ng-model is associated with. You do this specifically by adding a property called ng-model-options. The following should work:

<input type="text" ng-model="vm.man.name" ng-model-options="{debounce: 200}">
<input type="text" ng-model="vm.man.surName" ng-model-options="{debounce: 200}">

This adds a 200ms debounce(delay) before the model is updated. Once you do this, you can remove that timeout in the watch function. There are a few other properties that you can play around using ng-model-options as well. Go here for more info.

Jon
  • 2,456
  • 21
  • 28
  • thanks for your reply, anyway it does not work, it still sends two response to server if I press any keys 2 times – Dr. Abbos Oct 03 '17 at 02:39
  • That should work, did you increase the value? I had it at 200 but maybe you want 500ms instead. – Jon Oct 03 '17 at 05:31