1

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)

2 Answers 2

10

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
    });
}]);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.