Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Websocket and $rootScope.apply()

Tags:

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:

  1. Is this the expected behavior of angular that my list does not automatically get updated if I do not use $rootScope.apply() ?

  2. Why do I even need to wrap it in $rootScope.apply()?

  3. Is using $rootScope.apply() the correct way to solve this?

  4. Are there better alternatives to $rootScope.apply() for this problem?

like image 312
marius2k12 Avatar asked Feb 09 '14 11:02

marius2k12


People also ask

What is rootScope apply ()?

$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()

What is rootScope in angular?

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 the difference between rootScope and 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.

How many rootScope can Angular JS application have?

An app can have only one $rootScope which will be shared among all the components of an app.


1 Answers

  1. 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.

  2. 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.

  3. 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.

  4. 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

like image 51
Juliano Avatar answered Nov 11 '22 13:11

Juliano