Skip to content

Instantly share code, notes, and snippets.

@nl5887
Created December 30, 2013 09:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nl5887/8179591 to your computer and use it in GitHub Desktop.
Save nl5887/8179591 to your computer and use it in GitHub Desktop.
AngularJS websocket factory
app.factory('socket', function ($rootScope) {
var socket = new WebSocket("ws://localhost:8000/data");
return {
onopen: function (callback) {
socket.onopen = function () {
$rootScope.$apply(function () {
callback.apply(socket);
});
};
},
onmessage: function (callback) {
socket.onmessage = function (e) {
var data = e.data;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, [data]);
}
});
}
},
onerror: function (callback) {
socket.onerror = function (error) {
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, [error]);
}
});
};
},
send: function (message) {
socket.send(message);
}
};
});
/*
Usage:
app.controller('AppController', ['$rootScope', '$scope', '$log', 'socket', function($rootScope, $scope, $location, $log, socket) {
socket.onopen(function () {
});
socket.onerror(function (error) {
$log.error(error);
});
socket.onmessage(function (message) {
$log.info(message);
});
socket.send('message);
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment