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 correctly.
In the example below I've created a service which creates the websocket connection. If the websocket receives a message I just push that message into an array which contains all of the received messages.
In my controller I bind that array of messages to the scope and then use ng-repeat
to list them all in my partial view.
Service:
factory('MyService', [function() { var wsUrl = angular.element(document.querySelector('#ws-url')).val(); var ws = new WebSocket(wsUrl); ws.onopen = function() { console.log("connection established ..."); } ws.onmessage = function(event) { Service.messages.push(event.data); } var Service = {}; Service.messages = []; return Service; }]);
Controller:
controller('MyCtrl1', ['$scope', 'MyService', function($scope, MyService) { $scope.messages = MyService.messages; }])
Partial:
<ul> <li ng-repeat="msg in messages"> {{msg}} </li> </ul>
This however does not work correctly. When a new message is received and pushed into the array, the list that should display all messages does not get updated. I expected it to be updated because of angular two way data binding.
I've found one solution that works by wrapping the pushing of the message into a call to $rootScope.apply()
in the service:
ws.onmessage = function(event) { $rootScope.$apply(function() { Service.messages.push(event.data); }); }
My questions are:
Is this the expected behavior of angular that my list does not automatically get updated if I do not use $rootScope.apply()
?
Why do I even need to wrap it in $rootScope.apply()
?
Is using $rootScope.apply()
the correct way to solve this?
Are there better alternatives to $rootScope.apply()
for this problem?
$scope.$apply() This function is used to execute an expression in Agular. The function expression is optional and you can directly use $apply(). This is used to run watcher for the entire scope. $rootScope.$digest()
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.
The main difference is the availability of the property assigned with the object. A property assigned with $scope cannot be used outside the controller in which it is defined whereas a property assigned with $rootScope can be used anywhere.
An app can have only one $rootScope which will be shared among all the components of an app.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With