Skip to content

Instantly share code, notes, and snippets.

@nicksheffield
Created November 12, 2013 00:21
Show Gist options
  • Save nicksheffield/7423095 to your computer and use it in GitHub Desktop.
Save nicksheffield/7423095 to your computer and use it in GitHub Desktop.
Socket.io service for Angular.js
app.factory('socket', function ($rootScope) {
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
});
// End of useful code.
// Everything below is example of how to use
app.controller('myAppsCtrl', function($scope, socket){
socket.on('connected', function(){
console.log('Socket connected');
});
});
// credit: http://www.html5rocks.com/en/tutorials/frameworks/angular-websockets/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment