Socket.io在更新时运行函数

时间:2016-03-10 10:33:08

标签: angularjs sockets socket.io

当socket.io更新变量时,如何运行函数。似乎$ watch不起作用或者说我做错了。

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

1 个答案:

答案 0 :(得分:0)

由于封装,函数必须位于同一控制器/范围内。 $ scope的范围不知道socket.io是否更新变量,使用socket.on()监听器来触发angular $ watch

尝试此帖子中的代码Socket.IO message doesn't update Angular variable

而不是以角度观看$ watch,你可以使用socket.io

的socket.on()
 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; });
});
});

参见(最后的帖子)这个帖子 How do I use $scope.$watch and $scope.$apply in AngularJS?