I\'m currently playing around with an angular app that uses a websocket to communicate with the backend. I\'ve had some trouble getting angular\'s data binding working corre
Yes, AngularJS's bindings are "turn-based", they only fire on certain DOM events and on calls to $apply
/$digest
. There are some useful services like $http
and $timeout
that do the wrapping for you, but anything outside of that requires calls to either $apply or $digest.
You need to let AngularJS know you've changed a variable that's bound to a scope so it can update the view. There are other ways to do this though.
It depends on what you need. When wrap your code in $apply()
, AngularJS wraps your code in internal angularjs logging and exception handling, and when it's over, it propagates $digest
to all of your controller's scopes. In most cases, wrapping in $apply()
is the best way, it leaves more doors open for future features of angular you might end up to using. Is it the correct way? Read below.
If you don't use Angular's error handling, and you know your changes shouldn't propagate to any other scopes (root, controllers or directives), and you need to optimize for performance, you could call $digest
on specifically your controller's $scope
. This way the dirty-checking doesn't propagate. Otherwise, if you don't want errors to be caught by Angular, but need the dirty-checking to propagate to other controllers/directives/rootScope, you can, instead of wrapping with $apply
, just calling $rootScope.$apply()
after you made your changes.
Further reference: $apply vs $digest