0

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

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Sreekanth Reddy Balne
  • 3,264
  • 1
  • 18
  • 44

1 Answers1

1

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

georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • But there are multiple server side consumers with paths like `ws://myip:8010/notif/`, `ws://myip:8010/message/` etc. If I define a service and use a single connection, I won't be able to change it to a different path. Any suggestions? – Sreekanth Reddy Balne Dec 01 '18 at 17:19
  • In general directives shouldn't be making connections to the outside world, they should be communicating user events to the View controller and the View controller uses services to communicate business events to the outside world. – georgeawg Dec 01 '18 at 17:39
  • I just noticed your [previous question](https://stackoverflow.com/questions/53572062/angularjs-passing-a-function-along-with-scope-to-factory). It is in fact replacing the websocket with a new connection each time the constructor is called. – georgeawg Dec 01 '18 at 18:43