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 actually do and why does it need to be called to achieve the update?
value = "Click to Update Name forcefully." Output: Using $scope. $apply() call: In the above code, it can be seen that we have two buttons, but one button has an ng-click event to update the name whereas the other has a standard JavaScript listener to update the name.
$apply() function will execute custom code and then it will call $scope. $digest() function forcefully to check all watch list variables and update variable values in view if any changes found for watch list variables.
The Scope in AngularJS is the binding part between HTML (view) and JavaScript (controller) and it is a built-in object. It contains application data and objects. It is available for both the view and the controller. It is an object with available properties and methods.
In angularjs $digest() function is a central function of $scope object and it is used to iterate through the watch list items and check if any variable value has been modified or not.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With