Angular $scope.$digest vs $scope.$apply

In angularjs $scope object is having different functions like $watch(), $digest() and $apply() and we will call these functions as central functions.

The angularjs central functions $watch(), $digest() and $apply are used to bind data to variables in view and observe changes happening in variables.

Generally in angularjs we use $scope object to bind data to variables and use that variables values wherever we required in application. In angularjs whatever the variables we assigned with $scope object will be added to watch list by using $scope.$watch() function.

In angularjs once variables added to watch list $scope.digest() function will iterates through the watch list variables and check if any changes made for that variables or not. In case if any changes found for that watch list variables immediately corresponding event listener function will call and update respective variable values with new value in view of application.

The $scope.$apply() function in angularjs is used whenever we want to integrate any other code with angularjs. Generally the $scope.$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.

In most of the time angularjs will use $scope.watch() and $scope.digest() functions to check and update values based on the changes in variable values.


I think you must go through documents $apply

$apply() is used to execute an expression in angular from outside of the angular framework

Usually, you don't call $digest() directly in controllers or in directives. Instead, you should call $apply() (typically from within a directive), which will force a $digest().

Also as suggest by Jorg, use $timeout


$apply() and $digest() have some similarities and differences. They are similar in that they both check what's changed and update the UI and fire any watchers.

One difference between the two is how they are called. $digest() gets called without any arguments. $apply() takes a function that it will execute before doing any updates.

The other difference is what they affect. $digest() will update the current scope and any child scopes. $apply() will update every scope. So most of the time $digest() will be what you want and more efficient.

The final difference which explains why $apply() takes a function is how they handle exceptions in watchers. $apply() will pass the exceptions to $exceptionHandler (uses try-catch block internally), while $digest() will require you handle the exceptions yourself.

Tags:

Angularjs