Skip to content Skip to sidebar Skip to footer

Call Function With Delay When Textbox Changes In Angularjs

Can't seem to google up an example of how this is done. I have successfully created a textbox that calls a function every time it changes. What I would like to do is only call the

Solution 1:

There is ng-model-options for this manner

<inputid="delayedModel" ng-model="delayedModel" ng-change="callDelayed()" ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }" />

the callDelayed method only calls after 500 ms from typing the last char or on blur

Here is the documentation https://docs.angularjs.org/api/ng/directive/ngModelOptions

Solution 2:

For angular approach can inject $timeout in controller as dependency and use $watch on scope variable you've assigned in ng-model.

var timer=false;
$scope.ModelName='foo';
$scope.$watch('ModelName', function(){
  if(timer){
      $timeout.cancel(timer)
  }  
  timer= $timeout(function(){
      /* run code*/
   },delay)
});

Solution 3:

While @charlietfl provided totally acceptable answer I would like to share with you another approach without using $watch method:

Template:

<inputid="delayedModel" ng-model="delayedModel" ng-change="callDelayed()"/>

Controller:

    (function (timer, delay) {
        $scope.callDelayed= function () {
            if(timer){
                $timeout.cancel(timer)
            }
            timer = $timeout(function(){

                /* run code*/

            }, delay)
        };
    })(false, 500);

Maybe it's worth to point out why self-executing anonymous function is used. The main reason is to not pollute controller scope with time and delay variables. In this case they are defined in local function scope.

[UPDATE]

I've also found an interesting AngularJS project called angular-debounce that makes it really easy to achieve same effect. Using debounce directive it's possible to dealy model update like this:

<inputtype="text" ng-model="delayedModel" debounce="500"></input>

Post a Comment for "Call Function With Delay When Textbox Changes In Angularjs"