Skip to content

Instantly share code, notes, and snippets.

@ae6rt
Last active August 30, 2018 22:37
Show Gist options
  • Save ae6rt/7865161 to your computer and use it in GitHub Desktop.
Save ae6rt/7865161 to your computer and use it in GitHub Desktop.
An AngularJS websocket service that updates a controller scope variable
var app = angular.module('app', []);
app.controller('controller', function ($scope, websocketService) {
$scope.msg = "...";
websocketService.start("ws://localhost:8080/events", function (evt) {
var obj = JSON.parse(evt.data);
$scope.$apply(function () {
$scope.msg = obj.message
});
});
});
app.factory('websocketService', function () {
return {
start: function (url, callback) {
var websocket = new WebSocket(url);
websocket.onopen = function () {
};
websocket.onclose = function () {
};
websocket.onmessage = function (evt) {
callback(evt);
};
}
}
}
);
@andrei-m-code
Copy link

add method of sending data via socket and this will be pretty useful!

@MSandeep111
Copy link

Thanks $scope.$apply saves my day.

@CarKla
Copy link

CarKla commented Aug 30, 2018

Thanks a lot!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment