Skip to content

Instantly share code, notes, and snippets.

@ProLoser
Created July 19, 2013 17:19
Show Gist options
  • Save ProLoser/6040838 to your computer and use it in GitHub Desktop.
Save ProLoser/6040838 to your computer and use it in GitHub Desktop.
AngularJS: When to use $scope.$apply()?
/*** BAD: ***
* Never put $scope.$apply() deep down a call stack
* You may end up calling the same method inside a
* $digest, and find yourself using $scope.$$phase
* or $timeout to hack around it.
*/
setTimeout(function(){
a();
})
elm.bind('click', function(){
a();
})
socket.onmessage = function(){
a();
}
a = function() {
b();
}
b = function() {
c();
}
c = function() {
// do very specific logic
$scope.foo = bar;
// etc
$scope.$apply();
}
/*** GOOD: ***
* Always put $scope.$apply() at the TOP of your call stack
* make sure $apply() is as close to the async binding as possible
*/
setTimeout(function(){
$scope.$apply(function(){
a();
});
})
elm.bind('click', function(){
$scope.$apply(function(){
a();
});
})
socket.onmessage = function(){
$scope.$apply(function(){
a();
});
}
a = function() {
b();
}
b = function() {
c();
}
c = function() {
// do very specific logic
$scope.foo = bar;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment