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
320 views
in Technique[技术] by (71.8m points)

javascript - AngularJS unable to use scope inside a websocket callback

$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
  });
}])

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:

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

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

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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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


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

...