0

How do I run a function when socket.io updates a variable. It seems that $watch does not work or purhaps I am doing something wrong.

$http.get('/api/availabilitys/' + myId).then(response => {
  $scope.availability = response.data;
  socket.syncUpdates('availability', $scope.availability);
});


$scope.$watch('availability', function() {
  console.log('test'); //This is not printing on update
  angular.forEach(self.location, function (loc){
    loc.availability = $scope.availability.filter(function (a){
      return a.loc === loc._id;
    });
  });
});
Mika
  • 5,807
  • 6
  • 38
  • 83

1 Answers1

0

The functions have to be in the same controller / scope because of encapsulation. The $scope of angular does not know if socket.io updates a variable, use a socket.on() listener to trigger the angular $watch

Try the code in this thread Socket.IO message doesn't update Angular variable

Instead of $watch in angular you can use socket.on() of socket.io

 var container = angular.module("AdminApp", []);

 container.controller("StatsController", function($scope) {

var socket = io.connect();

socket.on('message', function (msg) {
    console.log(msg);
    $scope.$apply(function() { $scope.frontEnd = msg; });
});
});

See (the posts at the end of) this thread How do I use $scope.$watch and $scope.$apply in AngularJS?

Community
  • 1
  • 1
ralf htp
  • 9,149
  • 4
  • 22
  • 34
  • I know how to use $watch. My question is why is my socket update not triggering the $watch. – Mika Mar 10 '16 at 11:03
  • The $watch should work. What does not seem to work is the socket update. The socket update is outside of the 'scope' of angular see this thread http://stackoverflow.com/questions/30976934/socket-io-message-doesnt-update-angular-variable – ralf htp Mar 10 '16 at 11:12
  • My socket update is working as the $scope.availability variable is updating in the UI so angular is aware of it. – Mika Mar 10 '16 at 11:16
  • Is the variable 'avasilibility' defined inside the scope that the $watch listens to ? this is the key point... – ralf htp Mar 10 '16 at 11:30
  • Yes it is setup in the same scope. – Mika Mar 10 '16 at 11:33
  • try the socket.on() listener above. Maybe there has first to be executed a listener that triggers the $watch / $digest at all. See the last post of this thread http://stackoverflow.com/questions/15112584/using-scope-watch-and-scope-apply-in-angularjs – ralf htp Mar 10 '16 at 11:49