korotkin
1/21/2016 - 8:09 AM

AngularJS safe $apply (prevent "Error: $apply already in progress")

AngularJS safe $apply (prevent "Error: $apply already in progress")

$scope.safeApply = function(fn) {
  var phase = this.$root.$$phase;
  if(phase == '$apply' || phase == '$digest')
    this.$eval(fn);
  else
    this.$apply(fn);
};

// OR

function safeApply(scope, fn) {
  var phase = scope.$root.$$phase;
  if(phase == '$apply' || phase == '$digest')
    scope.$eval(fn);
  else
    scope.$apply(fn);
}