Last active
August 30, 2018 22:37
-
-
Save ae6rt/7865161 to your computer and use it in GitHub Desktop.
An AngularJS websocket service that updates a controller scope variable
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
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); | |
}; | |
} | |
} | |
} | |
); |
Thanks $scope.$apply saves my day.
Thanks a lot!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
add method of sending data via socket and this will be pretty useful!