Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
socket service in angular
//usage
app.controller('ChatCtrl', ['socket', function(socket){
socket.on('chat:messages', function(data){
$log.log('chat:messages', data);
$scope.messages = data.messages;
});
});
//socket service
app.factory('socket', ['$rootScope', '$log', '$timeout', function ($rootScope, $log, $timeout) {
var socket = io.connect();
$log.log('io', io);
$log.log('socket', socket);
socket.on('connect', function() {
$log.log('Connected!', arguments);
});
socket.on('error', function() {
$log.log('Error!', arguments);
});
socket.on('disconnect', function(){
$log.log("Disconnect!", arguments);
});
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$timeout(function () {
callback.apply(socket, args);
}, 0);
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
},
remove: function(name) {
socket.removeAllListeners(name);
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.