$apply and $watch

$apply
During the framework initialization, the compiler walks through the DOM tree looking for directives. When it finds the ngModel directive attached to any kind of input field, it binds its own scope's $apply function to the onkeydown event. This function is responsible for invoking the notification process of the framework called the digest cycle.

This cycle is responsible for the notification process by looping over all the watchers, keeping them posted about any change that may occur in the scope. There are situations where we might need to invoke this mechanism manually by calling the $apply function directly, as follows:
$scope.$apply(function () {
$scope.car.plate = '8AA5678';
});
On the other side, the components responsible for displaying the content of any element present inside the scope use their scope's $watch function to be notified about the changes on it. This function observes whether the value of a provided scope property has changed.

$watch
To illustrate the basic usage of the $watch function, let's create a counter to track the number of times the value of a scope property has changed. Consider the following code snippet in the parking.html file:
<input type="text" ng-model="car.plate" placeholder="What's the plate?"/>
<span>{{plateCounter}}</span>
Also, consider the following code snippet in the controllers.js file:
snippet
parking.controller("parkingCtrl", function ($scope) {
$scope.plateCounter = -1;
$scope.$watch("car.plate", function () {
$scope.plateCounter++;
});
});
Every time the plate property changes, this watcher will increment the plateCounter property, indicating the number of times it has changed. You may wonder why we are using -1 instead of 0 to initialize the counter, when the value starts with 0 in the view. This is because the digest cycle is called during the nitialization process and updates the counter to 0.

To figure it out, we can use some parameters inside the $watch function to know what has changed. When the $watch function is being initialized, newValue will be equal to oldValue, as shown in the following code snippet (the controllers.js file):
snippet
parking.controller("parkingCtrl", function ($scope) {
$scope.plateCounter = 0;
$scope.$watch("car.plate", function (newValue, oldValue) {
if (newValue == oldValue) return;
$scope.plateCounter++;
});
});
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +