Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
}
@akarelas

This comment has been minimized.

Copy link

@akarelas akarelas commented Sep 15, 2013

I even more like this, from this page:

    angular.module('ng').run(['$rootScope', function($rootScope) {
        $rootScope.safeApply = function(fn) {
            var phase = this.$root.$$phase;
            if(phase == '$apply' || phase == '$digest') {
                if(fn && (typeof(fn) === 'function')) {
                    fn();
                }
            } else {
                this.$apply(fn);
            }
        };
    }]);
@amatiasq

This comment has been minimized.

Copy link

@amatiasq amatiasq commented Jan 28, 2016

@akarelas This does the same but looks more readable to me

angular.module('ng').run(['$rootScope', function($rootScope) {
  $rootScope.safeApply = function safeApply(operation) {
    var phase = this.$root.$$phase;
    if (phase !== '$apply' && phase !== '$digest') {
      this.$apply(operation);
      return;
    }

    if (operation && typeof operation === 'function')
      operation();
  };
}]);
@Hank-wood

This comment has been minimized.

Copy link

@Hank-wood Hank-wood commented Apr 29, 2017

i have issue
somethims this.$root.$$phase is undefined

route.js:806 Uncaught TypeError: Cannot read property '$$phase' of null
    at p.$rootScope.safeApply

change like this?


angular.module('ng').run(['$rootScope', function($rootScope) {
    $rootScope.safeApply = function(fn) {
        
        if (this.$root && this.$root.$$phase) {
            var phase = this.$root.$$phase;
            if (phase == '$apply' || phase == '$digest') {
                if (fn && (typeof(fn) === 'function')) {
                    fn();
                }
            } else {
                this.$apply(fn);
            }
        } else {
            $scope.$apply(fn);
          
        }

    };
}]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.