Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent button from being pressed twice

I am new to JavaScript and AngularJS. I have made a demo in that I made simple page navigation with modal, so when I click on a button I am going to another page. But my problem is when I click on that button twice it opens the same page twice. I have used timeout function but I don't know why it is not working on my demo, my code is as below.

JavaScript

$scope.foo = function() {
        if ($scope.filterflg !== "1" ) {
            $scope.filterflg = "1";
             $scope.disabled = true;


            gallery.pushPage("filter.html", {
                params: FkCategory
            });

            $timeout(function() {
                console.log("====timeout occured===");
                $scope.filterflg = "0";
                  $scope.disabled = false;
            }, 3000);
        }
    };

HTML

   <span class="toolbar-button--quiet navigation-bar__line-height" ng-click="foo();" ng-disabled="disabled"
                  style="border: none; padding: 0 5px 0 0;">
like image 766
JIGAR Avatar asked Dec 29 '25 20:12

JIGAR


1 Answers

setTimeout wouldn't modify the scope, because it's a native JavaScript function, which will run outside AngularJS context, and the the code which runs outside AngularJS context which is changing AngularJS scope will not reflect on the UI until you run the digest cycle manually.

So instead of using setTimeout you should use $timeout which will run a digest cycle for you.

Another reason behind the user is able to click button twice is you have 2000ms (2sec) of timeout which is too much; reduce that as you want will make an immediate effect.

$timeout(function() {
    disabled = false;
}, 0);
like image 177
Pankaj Parkar Avatar answered Jan 01 '26 10:01

Pankaj Parkar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!