Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

javascript - Angular - Websocket and $rootScope.apply()

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...