forked from angular/angular.js
-
Notifications
You must be signed in to change notification settings - Fork 10
When to use $scope.$apply()
ProLoser edited this page Mar 19, 2013
·
1 revision
AngularJS provides wrappers for common native JS async behaviors:
- Events =>
ng-click
- Timeouts =>
$timeout
- jQuery.ajax() =>
$http
This is just a traditional async function with a $scope.$apply()
called at the end, to tell AngularJS that an asynchronous event just occurred.
You should try to put $apply
as close to where the asynchronous event is registered as possible. If you don't know why Angular isn't refreshing and start lacing an $apply
in random functions, you will find that sometimes it's superfluous and other times you'll simply get errors.
If there is an Angular equivalent, you should probably be using it instead. If you're creating an AngularJS version (such as for sockets) your general-purpose socket-wrapper should have a $scope.$apply()
anywhere you fire a callback.