AngularJS无法在websocket回调中使用范围

AngularJS无法在websocket回调中使用范围

本文介绍了AngularJS无法在websocket回调中使用范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ scope 在回调函数中无效。

$scope is not working inside a callback function.

angular.
module('common').
controller('bidVBoxController', ['$scope', '$location','$element', 'Socket', 'Bid',
 function($scope, $location, $element, Socket,Bid){
  var self = this;
  self.socket = new Socket("ws://192.168.225.59:8010/ws/bidData/");
  $scope.placeBid = function(){
    self.socket.send({
      type: "place_bid",
      data: {
        bidId: $scope.bid.id
      }
    });
  };
  console.log($scope.bid);
  $scope.bid.top_bid_data="sss";//This works.
  self.socket.onmessage(function(event) {
      var data = JSON.parse(event.data);
      console.log($scope.bid);//This doesn't work
      $scope.bid.top_bid_data=data["message"];//This doesn't work
  });
}])

回调函数传递给 self.socket.onmessage ,它应该更新 $ scope 变量。但它似乎不起作用。请帮忙。

A callback function is passed to the self.socket.onmessage, which is supposed to update $scope variable. But it appears that doesn't work. Please help.

Update1:​​

此控制器与指令一起使用 bidVBox 并且有多个元素:

This controller is used with a directive bidVBox and there are multiple elements:

<bid-v-box ng-repeat="bid in bids">
</bid-v-box>

当在第一个 bid-v-box中执行回调函数时/ code>元素的控制器, $ scope.bid.top_bid_data = data [message]; 更新最后一个元素的范围而不是第一个元素的范围。我也尝试使用 $ scope。$ apply(function(){$ scope.bid.top_bid_data = data [message];})。但这不起作用。

When the callback function is executed in the first bid-v-box element's controller, $scope.bid.top_bid_data=data["message"]; updates the scope of the last element and not the first one. I have also tried using $scope.$apply(function(){$scope.bid.top_bid_data=data["message"];}). But that didn't work.

推荐答案

将websocket构造函数移动到服务并仅使用一个连接会更明智。正如所写, ng-repeat 正在创建与服务器的多个websocket连接。服务器端应用程序以不同方式处理每个连接。显然,服务器正在响应最后一次连接而不是单独连接。有关详细信息,请参阅。

It would be wiser to move the websocket constructor to a service and use only one connection. As written the ng-repeat is creating multiple websocket connections to the server. It is up to the server side application to treat each connection differently. Evidently the server is responding to the last connection made instead of each individually. For more information, see Stackoverflow: Multiple Websockets.

请参阅还

See also Github WS Issue #684 - Multiple connections, but single websocket.on("message") event emitter

这篇关于AngularJS无法在websocket回调中使用范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:40