How to correctly fix the AngularJS error: "digest already in progress"


$digest already in progress

First of all, don’t fix it this way

if ( ! $scope.$phase) { 
  $scope.$apply(); 
}

It makes no sense because $phase is just a boolean flag for $digest cycle, so your $apply() sometimes won’t run. And remember it’s a bad practice.

Instead, use $timeout

$timeout(function(){ 
  // Any code in here will automatically have an $scope.apply() run afterwards 
  $scope.myvar = newValue; 
  // And it just works! 
});

If you are using underscore or lodash, you can use defer():

_.defer(function(){ 
  $scope.$apply(); 
});

Via Stackoverflow