I've setup an AngularJS app using websockets and it seems to be working. Here is a summary of whats going on:
var app = angular.module('websocketApp',[]);
app.factory('WebSocket',function($rootScope) {
var websocket = new WebSocket(websocket_url);
var items = [];
websocket.onmessage = function(msg) {
items.push(JSON.parse(msg.data));
$rootScope.$broadcast('new_message');
}
return {
fetchItems: function() {
return items;
}
}
});
app.controller('ItemsCtrl',function($scope,WebSocket) {
$scope.$on('new_message',function() {
$scope.$apply(function() {
$scope.items = WebSocket.fetchItems();
});
});
});
My question is if anyone else has setup an Angular app using websockets and if this implementation is the correct way to go about it or if there is a better solution. I've read many cons on using $broadcast but this seems to be the correct usage of the $broadcast functionality.