[AngularJS] Safe Scope.$apply Implementation (Error: $apply already in progress)


One of the headaches of writing one's own directives or services of AngularJS application is that get the following error message while the $apply method of scope is called:

Error: $apply already in progress

The following is my solution (call the following safeApply method instead of $apply):

$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);
}

The fn in above sample code could be AngularJS expression or JavaScript function, depending on your need.


References:

[1]my gist
[2]angularjs - Prevent error $digest already in progress when calling $scope.$apply() - Stack Overflow
[3]'Safe' $apply in Angular.JS