Created
July 11, 2015 06:27
-
-
Save anonymous/f2d5660662e3b69cc78e to your computer and use it in GitHub Desktop.
socket service in angular
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//usage | |
app.controller('ChatCtrl', ['socket', function(socket){ | |
socket.on('chat:messages', function(data){ | |
$log.log('chat:messages', data); | |
$scope.messages = data.messages; | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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