1

I'm using angular.js with stomp-websockets,sock.js under by this tutorial http://g00glen00b.be/spring-websockets-angular/. I'm getting messages from websocket, but template view isn't refreshed after message from websocket is arrived. When I want to update template view I need to clear input box, or scroll with mouse.

$scope.initiator = false;   
$scope.socket = {
    client: null,
    stomp: null
};

$scope.initSockets = function() {
   $scope.socket.client = new SockJS('/myUrl');
   $scope.socket.stomp = Stomp.over($scope.socket.client);

   $scope.notifyMessage = function(message) {
       $scope.initiator = true;
       $scope.messages.push(message)
   };

   $scope.socket.stomp.connect({}, function() {         
       $scope.socket.stomp.subscribe("/topic/messages", $scope.notifyMessage);                      
   });      

   $scope.socket.client.onclose = $scope.reconnect;     
};

$scope.initSockets();   


template view:
<ul><li ng-repeat="item in messages track by $index">{{item}}</li></ul>
4

1 回答 1

1

您可能需要使用 scope.$apply 才能使其生效。afaics sock.js 不是为 Angular 制作的,因此您需要让 Angular 知道范围内发生了某些变化。您可以使用 scope.$apply 执行此操作。

$scope.notifyMessage = function(message) {
   $scope.$apply(function(){
       $scope.initiator = true;
       $scope.messages.push(message)
   });
};
于 2014-06-11T12:08:13.533 回答