Jitender
Jitender

Reputation: 7971

Delay code using debounce in angularjs

I have to write email verification function in angularjs. I want to make a post request after 2 second when user has done editing with email id. Is there any pre defined method in angularjs for this. fiddle

var app = angular.module('form-example', []);
    app.controller('formctrl',function($scope){
        var ctrl= this;
        ctrl.verifyEmail= function(){    
        console.log('hiiii')
        }

    })

Upvotes: 16

Views: 31288

Answers (2)

Hari Das
Hari Das

Reputation: 10864

You can use ng-model-options to delay the model update. Here is an working example. This feature was added in Angular 1.4+.

var app = angular.module("myApp", []); 
app.controller("myCtrl", function($scope) {
    
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<script>

</script>

<div ng-app="myApp" ng-controller="myCtrl">
  <input ng-model="email" ng-model-options="{ debounce: 2000 }"/>
  <br/><br/>
  The email will be updated here after 2 seconds: <strong>{{email}}</strong>
</div>

</body>
</html>

Upvotes: 8

Moncef Hassein-bey
Moncef Hassein-bey

Reputation: 1361

You can use angular $timeout service.

var app = angular.module('form-example', []);
    app.controller('formctrl',function($scope, $timeout){
        var ctrl= this;
        ctrl.verifyEmail= function(){    
           $timeout(function(){
               console.log('hiiii');
           }, 2000); 
        }

    })

Upvotes: 0

Related Questions