Last active
April 7, 2020 08:49
-
-
Save siongui/4969449 to your computer and use it in GitHub Desktop.
AngularJS safe $apply (prevent "Error: $apply already in progress")
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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 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();
};
}]);
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
I even more like this, from this page: