I\'ve been using $scope.$apply()
to update the bindings for my models when I receive data through websockets in my Angular apps and it works. But what does it a
From the Angular docs:
$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life-cycle of exception handling, executing watches.
The documentation also provides a pseudo-code of it:
function $apply(expr) {
try {
return $eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
}
In short, $apply
evaluates an expression and triggers a digest cycle, making Angular execute all registered watch listeners and update any view bindings.
Finally, you've said that you've been using $apply
to update the bindings for your models, but that is only required when the update comes from outside Angular. In most cases you don't need to call it manually.
If you call $apply
the code provided will be executed in angular-context
which you can make use of what angular provides.
From the link:
Angular modifies the normal JavaScript flow by providing its own event processing loop. This splits the JavaScript into classical and Angular execution context. Only operations which are applied in Angular execution context will benefit from Angular data-binding, exception handling, property watching, etc...
You can also use $apply() to enter Angular execution context from JavaScript. Keep in mind that in most places (controllers, services) $apply has already been called for you by the directive which is handling the event. An explicit call to $apply is needed only when implementing custom event callbacks, or when working with third-party library callbacks.
Simply put it:
I also wrote a blog entry about what $apply, $digest and $watch do and how they work together
I hope that helps.