【发布时间】:2014-07-14 14:11:38
【问题描述】:
我已经使用 websockets 设置了一个 AngularJS 应用程序,它似乎正在工作。以下是正在发生的事情的摘要:
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();
});
});
});
我的问题是,是否有其他人使用 websockets 设置了 Angular 应用程序,以及此实现是否是正确的方法,或者是否有更好的解决方案。我读过很多关于使用 $broadcast 的缺点,但这似乎是 $broadcast 功能的正确用法。
【问题讨论】:
标签: angularjs websocket broadcast