0

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.

Akshay Khetrapal
  • 2,586
  • 5
  • 22
  • 38
  • This will be useful for you i think so http://stackoverflow.com/questions/21138388/angular-js-identify-an-digest-complete-event-and-removing-from-url-in-angular – Deepak Aug 30 '16 at 11:39
  • I do not see why the `$timeout` whould be "anti-logic" as it waits for the digest cycle to finish before it fires the callback. – cbass Aug 30 '16 at 11:40
  • cbass, wouldn't it run the digest cycle again? – Akshay Khetrapal Aug 30 '16 at 11:41

3 Answers3

0

try this:

$scope.names = [];
$scope.disableButton = true;
FetchNames.getAllNames().then(function(result){
  // if in digest; reuturn
  if($scope.$$phase || $scope.$root.$$phase ){return}
  result.data.forEach(function(name){
    $scope.names.push(name);
  });
$scope.disableButton = false;
});
kwoktung
  • 572
  • 1
  • 4
  • 12
0

i think this will help you

Angular JS identify an digest complete event and removing # from url in angular js during viewchange

and this link

Community
  • 1
  • 1
Deepak
  • 1,373
  • 2
  • 10
  • 31
-1

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;
     };
shobhit jain
  • 141
  • 1
  • 9