Delay code using debounce in angularjs

妖精的绣舞 提交于 2021-02-07 05:15:38

问题


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')
        }

    })

回答1:


The debounce comes built in with Angular 1.3+. As you'd expect, it's implemented as a directive. You can do this:

<input ng-model='address' ng-model-options="{ debounce: 500 }" />

The $scope.address attribute is not updated until 500ms after the last keystroke.

If you need more control

If you want more granularity, you can set different bounce times for different events:

<input ng-model='person.address' ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }" />

Here for example we have a 500ms bounce for a keystroke, and no bounce for a blur.

Documentation

Read the documentation here: https://docs.angularjs.org/api/ng/directive/ngModelOptions




回答2:


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>



回答3:


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); 
        }

    })


来源:https://stackoverflow.com/questions/32589154/delay-code-using-debounce-in-angularjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!