Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason to use $scope.$apply rather than $applyAsync?

Tags:

angularjs

What would be a use case for calling $scope.$apply rather than $applyAsync? I'm probably missing something, but the latter just seems like a safer version of the former, so you can't get digest reentrancy.

like image 810
Wolf Avatar asked Dec 02 '15 18:12

Wolf


People also ask

What is use of scope apply?

The $scope. $apply() function is used to execute some code, and then call $scope. $digest() after that, so all watches are checked and the corresponding watch listener functions are called. The $apply() function is useful when integrating AngularJS with other code.

What is the use of $rootScope?

All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive. The rootScope is available in the entire application. If a variable has the same name in both the current scope and in the rootScope, the application uses the one in the current scope.

What is evalAsync?

$evalAsync([expression], [locals]); Executes the expression on the current scope at a later point in time. The $evalAsync makes no guarantees as to when the expression will be executed, only that: it will execute after the function that scheduled the evaluation (preferably before DOM rendering).

How many $rootScope an AngularJS application can have?

The scope in AngularJS is hierarchical in nature: The $rootScope acts as a global variable. All the $scopes of an AngularJS application are children of the $rootscope. An app can have only one $rootScope.


1 Answers

$scope.$apply will try to apply the given expression immediately, meaning that if a digest cycle is currently being run, you may end up getting an error/exception.

$applyAsync on the other hand will "schedule" the expression to be applied in about 10 milliseconds (as per the docs), so that you are able to queue more than one expression in the same digest cycle.

like image 126
taxicala Avatar answered Oct 04 '22 03:10

taxicala