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;
    });
  });
});
2
  • in your $http.get after updating the values, try doing $scope.$apply() Commented Mar 10, 2016 at 10:58
  • Does not help. The test prints the first time around. It does not print on update. Commented Mar 10, 2016 at 11:01

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

6 Comments

I know how to use $watch. My question is why is my socket update not triggering the $watch.
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 stackoverflow.com/questions/30976934/…
My socket update is working as the $scope.availability variable is updating in the UI so angular is aware of it.
Is the variable 'avasilibility' defined inside the scope that the $watch listens to ? this is the key point...
Yes it is setup in the same scope.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.