Akshay Khetrapal Akshay Khetrapal - 3 months ago 18
AngularJS Question

Prevent button click while digest cycle is running in angular

I am updating the $scope on a button click which basically makes a Restangular call, fetches data and populates the $scope variable.

However, if the user clicks the button multiple times while a $digest cycle is running, the $scope gets updated with duplicated values.

I am pretty sure it's a common problem. However, I haven't come across one on SO with a solution I am looking for.

People have suggested using

$timeout
but it seems anti-logic.

I'd rather just disable the button while the
$digest
cycle is running.

Here's what I've implemented so far.

$scope.names = [];
$scope.disableButton = true;
FetchNames.getAllNames().then(function(result){
result.data.forEach(function(name){
$scope.names.push(name);
});
$scope.disableButton = false;
});


Here, the button is disabled while the promise is getting resolved.
But that doesn't solve my problem. I need to check when the digest cycle is completed.

Answer

use ng-disabled built-in directive to disable button when user click it. to achieve this just set a variable to true. Look at the code below

<button ng-click="btn1=true, yourFunction()" ng-disabled='btn1'>

which in your controller can be like this

    $scope.btn1= false;
    $scope.yourFunction= function(){
      $scope.names = [];
      FetchNames.getAllNames().then(function(result){
        result.data.forEach(function(name){
          $scope.names.push(name);
       });
       $scope.disableButton = false;
     };