Reputation: 349
I have several controllers. In one of them, i need to open web socket connection. In another i need to listen messages and if needed update $scope. Please help me do that on example below:
app.controller('MainCtrl', ['$scope', function($scope) {
$scope.testProp = {};
$scope.testProp2 = '';
// listen messages here
// and update $scope.testProp && $scope.testProp2
}]);
app.controller('SearchCtrl', ['$scope', function($scope) {
// open connection here
}]);
P.S. i understand that the problem is trivial, but i am new in AngularJS and WebSockets, i need help, and now i don't have time for learn docs (what will i do later)
Upvotes: 1
Views: 17779
Reputation: 349
I found a simple solution with factories:
app.factory('socket', [function() {
var stack = [];
var onmessageDefer;
var socket = {
ws: new WebSocket(websocket_url),
send: function(data) {
data = JSON.stringify(data);
if (socket.ws.readyState == 1) {
socket.ws.send(data);
} else {
stack.push(data);
}
},
onmessage: function(callback) {
if (socket.ws.readyState == 1) {
socket.ws.onmessage = callback;
} else {
onmessageDefer = callback;
}
}
};
socket.ws.onopen = function(event) {
for (i in stack) {
socket.ws.send(stack[i]);
}
stack = [];
if (onmessageDefer) {
socket.ws.onmessage = onmessageDefer;
onmessageDefer = null;
}
};
return socket;
}]);
when
app.controller('MainCtrl', ['$scope', 'socket', function($scope, socket) {
socket.onmessage(function(event) {
//var data = JSON.parse(event.data);
//$scope.testVar =
});
}]);
app.controller('SearchCtrl', ['$scope', 'socket', function($scope, socket) {
socket.send({
//somedata
});
}]);
Upvotes: 10
Reputation: 35915
Please take a look at this answer : AngularJS and WebSockets beyond
Basically it is an example about creating a WebSocket service in AngularJS that can be used to request/response and publish/subscribe.
Upvotes: 0