This article will explain the working of various functions of Angular.js- $scope.$digest(), $scope.$apply(), $rootScope.$digest(), $rootScope.$apply().
Introduction
This article will explain the working of various functions of AngularJS- $scope.$digest(), $scope.$apply(), $rootScope.$digest(), $rootScope.$apply().
The example below demonstrates the working of all the above functions.
Create the HTML and JS file as below.
Index.html
myScript.js
Open the index.html file in the browser.
Note: For every button click, we have done increment by 1 for the RootScope 'val' and scope 'val'.
RootScope val = 1and val1 = 1, val2 = 1, val3 = 1, val4 = 1.
RootScope val = 1
and val1 = 1, val2 = 1, val3 = 1, val4 = 1.
RootScope val = 2val1 = 2, val2 = 1, val3 = 1, val4 = 1.
RootScope val = 2
val1 = 2, val2 = 1, val3 = 1, val4 = 1.
RootScope val = 3val1 = 2, val2 = 2, val3 = 1, val4 = 1.The values of Controller2 have been updated because we have called the digest manually inside it.
RootScope val = 3
val1 = 2, val2 = 2, val3 = 1, val4 = 1.
The values of Controller2 have been updated because we have called the digest manually inside it.
RootScope val = 4val1 = 2, val2 = 2, val3 = 2, val4 = 1Also, all the scope has been updated because we have called 'apply' function that starts the watcher of values for all the scope variables.
RootScope val = 4
val1 = 2, val2 = 2, val3 = 2, val4 = 1
Also, all the scope has been updated because we have called 'apply' function that starts the watcher of values for all the scope variables.
RootScope val = 5val1 = 2, val2 = 2, val3 = 3, val4 = 4.This also updates all the scope watched values as it is equivalent to the $scope.$apply().
RootScope val = 5
val1 = 2, val2 = 2, val3 = 3, val4 = 4.
This also updates all the scope watched values as it is equivalent to the $scope.$apply().
$watch()
This function is attached to all the scope variables that we declared. Any changes to the value have been watched here in this function to update the binding of values from UI to Controller and vice versa.
This function is also used to add specific type values with the help of its parameters 'oldValue' and 'newValue' inside it.
Learn $watch for more details.
Azure in 24 Days