1

I've just come on board to a new project and I see this pattern alot in angular js code:

_.defer(function () {
$scope.$apply();
});

This seems wrong to me but I'm not sure why. What are possible reasons that you would you wait for angular's interpolation to finish and then call $scope.$apply() again?

1
  • 1
    maybe to avoid the error "digest already in progress". A variable can be changed while Angular is "digesting" the data. so maybe this change can be not detected by angular so an "$apply" is needed. My 2cents Commented Apr 15, 2016 at 14:04

1 Answer 1

3

$apply() calls $digest()

Under the hood, $digest is angular's internal loop to check if any binded data has changed. Most of the time, you don't need to call $apply yourself because AngularJS takes care of this.

The only cases you need to call $apply is when you use an external lib (for instance when you wrap a jquery lib inside a directive or when using a asynchronous lib such as facebook/twitter) and angular could not possibly know about the DOM changes.

In these cases, you could wrap your code inside $timeout. It is just a safe way for angular to call $apply when its ready rather than risking the error '$digest already in progress error' is you directly call $apply.

$timeout (function () {
  $scope.update = "something has changed";
});

This way is more the native angular way rather than using the underscore library.

For detailed explanations you can check out this article (a bit old but the core principles of angular stay the same).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.