This may occur if you call $scope.apply
while the digest
function is being called. Meaning and most likely your scope.apply is not required.
From Angular Docs: $digest()
Processes all of the watchers of the current scope and its children. Usually, you don't call $digest()
directly in controllers or in directives.
Angular keeps track of what phase of processing we are in, the relevant ones being $apply and $digest. Trying to reenter a $digest or $apply while one of them is already in progress is typically a sign of programming error that needs to be fixed. So Angular will throw this error when that occurs. Click Here for more details
Your code reminds an old trick that needed to be implemented in earlier versions of angular(0.4 or 0.8) but as far as recall it is not required in the version of angular that you are using.
Also note that Angular Team offered us a way to diagnose this type of errors:
When you get this error it can be rather daunting to diagnose the cause of the issue. The best course of action is to investigate the stack trace from the error. You need to look for places where $apply or $digest have been called and find the context in which this occurred.
There should be two calls:
The first call is the good $apply/$digest and would normally be triggered by some event near the top of the call stack.
The second call is the bad $apply/$digest and this is the one to investigate.
Once you have identified this call you work your way up the stack to see what the problem is.
If the second call was made in your application code then you should look at why this code has been called from within a $apply/$digest. It may be a simple oversight or maybe it fits with the sync/async scenario described earlier.
If the second call was made inside an Angular directive then it is likely that it matches the second programmatic event trigger scenario described earlier. In this case you may need to look further up the tree to what triggered the event in the first place.