Sometimes I need to use $scope.$apply
in my code and sometimes it throws a "digest already in progress" error. So I started to find a way around this and found this question: AngularJS : Prevent error $digest already in progress when calling $scope.$apply(). However in the comments (and on the angular wiki) you can read:
Don't do if (!$scope.$$phase) $scope.$apply(), it means your $scope.$apply() isn't high enough in the call stack.
So now i have two questions:
- Why exactly is this an anti-pattern?
- How can i safely use $scope.$apply?
Another "solution" to prevent "digest already in progress" error seems to be using $timeout:
$timeout(function() {
//...
});
Is that the way to go? Is it safer? So here is the real question: How I can entirely eliminate the possibility of a "digest already in progress" error?
PS: I am only using $scope.$apply in non-angularjs callbacks that are not synchronous. (as far as I know those are situations where you must use $scope.$apply if you want your changes to be applied)
scope
from within angular or from outside of angular. So according to this you always know, if you need to callscope.$apply
or not. And if you are using the same code for both angular/non-angularscope
manipulation, you're doing it wrong, it should be always separated... so basically if you run into a case where you need to checkscope.$$phase
, your code is not designed in a correct way, and there is always a way to do it 'the right way' – doodeecdigest already in progress
error – doodeec