Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Function with Delay When Textbox Changes in AngularJS

Tags:

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 function when the user has stopped typing for x milliseconds.

I know how to do it in JQuery using the keyup event, and can probably make it work this way, but want to do it "the Angular Way".

Edit

Maybe it wasn't clear from the tag or text, but I am using AngularJS, and want to use correct methodology for that framework to create this delay functionality.

like image 742
Phil Sandler Avatar asked Mar 30 '13 20:03

Phil Sandler


2 Answers

There is ng-model-options for this manner

<input id="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

like image 104
Reza Avatar answered Oct 30 '22 00:10

Reza


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) }); 
like image 34
charlietfl Avatar answered Oct 30 '22 02:10

charlietfl