Skip to content

Instantly share code, notes, and snippets.

@PatrickJS
Created August 25, 2013 16:58
Show Gist options
  • Select an option

  • Save PatrickJS/6334981 to your computer and use it in GitHub Desktop.

Select an option

Save PatrickJS/6334981 to your computer and use it in GitHub Desktop.
If you find yourself triggering the '$apply already in progress' error while developing with Angular.JS (for me I find I hit most often when integrating third party plugins that trigger a lot of DOM events), you can use a 'safeApply' method that checks the current phase before executing your function. I usually just monkey patch this into the $s…
.factory('safeApply', ['$rootScope', function($rootScope) {
return function($scope, fn) {
var phase = $scope.$root.$$phase;
if(phase == '$apply' || phase == '$digest') {
if (fn) {
$scope.$eval(fn);
}
} else {
if (fn) {
$scope.$apply(fn);
} else {
$scope.$apply();
}
}
}
}])
.controller('MyCtrl', ['$scope,' 'safeApply', function($scope, safeApply) {
safeApply($scope); // no function passed in
safeApply($scope, function() { // passing a function in
});
}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment