What is Digest
Cycle In AngularJS ?
Digest Cycle is responsible for two
way binding. When A directive like ng-model having some value in the input control which is from $scope object of
the controller , if user changes the exisiting value with some new value, then
internally this Digest Cycle evauates.
In
this Digest Cycle mainly three functions come in front, those are $watch(), $digest()
and $apply().
$apply() : When any event is fired
like ng-click or ng-model value is changed in input control. Then
$scope.$apply() is called, then the Digest Cycle starts and this
$scope.$apply() calls the $rootscope.$digest(), , again this calls the child
$scope objects of the controllers, where this each child $scopes calls the
corresponding $watch().
In
some scenarios, we have to call this $scope.$apply() manually, like when we
want to update any model outside of the Angular context like
setTimeout(),setupReader, any DOM events, then we have to use $scope.apply()
manually.
Syntax:
$scope.$apply(function(){
// some code here
})
Or
in some DOM events or in some event listeners the syntax is also as follows:
Syntaxt
:
$scope.$apply();
$digest() : After $scope.$apply() is
called internally, the Digest Cycle is starts and calls the $rootscope.$digest
which calls child $scope objects $scope.$digest() which in turn calls
corresponding $watch() and after completion of all watchers functionality i.e.,
if any changes in the value of the $scope objects, then it will update and also
once again runs the $digest() to recheck, which is called Dirty
Checking.
$watch() : After $scope.$digest()
calls $watch(), $watch() watches the $scope of objects of the controller
internally when any event is fired like ng-click or ng-model value is changed
in input control. Actually $watch() is a listener, if any change is there in
value of ng-model then it will update the model and shows the updated value in
the view. We can declare $watch() by ourselves also.
Syntax
:
$watch(CorrespondentVariable,
Listener ,[ObjectEquality]);
Here
Correspondent
Variable is a string Of “VariableName”
Or function that returns variable itself
Here
Listener is a function that is having arguments of old value and new value as
function(newvalue,oldvalue){
}
ObjectEquality
Is a boolean value, i.e., true then it will compare the references of the
object or else if it is false, then no comparision takes place (instead of
putting false, we can remove the objectEquality)
No comments:
Post a Comment
Note: only a member of this blog may post a comment.