Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

angularjs - Preventing / dealing with double button clicks in angular

In angular we can set up a button to send ajax requests like this in view:

... ng-click="button-click"

and in controller:

...
$scope.buttonClicked = function() {
   ...
   ...
   // make ajax request 
   ...
   ...
}

So to prevent a double submit I could set a flag to buttonclicked = true when a button is click and unset it when the ajax callback is finished. But, even then control is handled back to angular who will updates to the Dom. That means there is a tiny window where the button could be clicked again before the original button click has completely 100% finished.

It's a small window but can still happen. Any tips to completely avoid this from happening - client side i.e. without making any updates to server.

Thanks

question from:https://stackoverflow.com/questions/18130808/preventing-dealing-with-double-button-clicks-in-angular

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First you'd better add ngDblclick, when it detects the double click just return false:

<ANY ng-click="buttonClicked()" ng-dblclick="return false">

If you want to wait for the Ajax call to be finished, then you can disable the button by setting the ng-disabled

<ANY ng-click="buttonClicked()" ng-dblclick="return false;" ng-disabled="flag">

And in your controller, you can do

$scope.flag = false;
$scope.buttonClicked = function() {
    $scope.flag = true;
    Service.doService.then(function(){
        //this is the callback for success
        $scope.flag = false;
    }).error(function(){
        //this is the callback for the error
        $scope.flag = false;
    })
}

You need to handle both case when the ajax call is successfull or failed, since if it is failed, you don't want it show as diabled to confuse user.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...