Usually the socket.io's on
method is like this:
socket.on('/msg', function(data){});
But in Angular that callback has to be wrapped inside its $rootScope.$apply()
method otherwise anything that happens in the callback (like changing $scope
properties) doesn't update in Angular.
Here's a simple way to do that:
function socketFactory($rootScope) {
return {
emit: socket.emit.bind(socket),
on: function(msg, callback) {
socket.on(msg, function() {
var args = arguments;
$rootScope.$apply(function(){
callback.apply(socket, arguments)
});
});
},
};
};
I was able to shorten this a little bit:
on: function(msg, callback) {
socket.on(msg, function() {
$rootScope.$apply(callback.apply(socket, arguments));
});
},
I'm not sure if it'll go any further but I tried:
on: function(msg, callback) {
socket.on(msg, $rootScope.$apply.apply(null, callback));
},
which threw an error:
Uncaught TypeError: Cannot read property 'apply' of undefined socket.io.js:1194
I'm guessing $apply.apply
doesn't work.