AngularJS combined with the power of WebSockets

I am currently working on a project that involves multiple controllers. One of these controllers requires me to establish a web socket connection, while another needs to listen for messages and update the $scope if necessary. Can you please help me by providing an example similar to the one below:

app.controller('MainCtrl', ['$scope', function($scope) {
    $scope.testProp = {};
    $scope.testProp2 = '';
    // code to listen for messages here and update $scope.testProp && $scope.testProp2
}]);

app.controller('SearchCtrl', ['$scope', function($scope) {
    // code to open web socket connection here
}]);

P.S. I realize that this issue may seem straightforward, but as someone new to AngularJS and WebSockets, I would greatly appreciate any assistance. Unfortunately, I don't have much time to dive into the documentation at the moment.

Answer №1

After exploring various options, I came up with an elegant solution using factories:

app.factory('socket', [function() {
    var messageQueue = [];
    var deferredCallback;
    var socket = {
        ws: new WebSocket(websocket_url),
        send: function(data) {
            data = JSON.stringify(data);
            if (socket.ws.readyState == 1) {
                socket.ws.send(data);
            } else {
                messageQueue.push(data);
            }
        },
        onmessage: function(callback) {
            if (socket.ws.readyState == 1) {
                socket.ws.onmessage = callback;
            } else {
                deferredCallback = callback;
            }
        }
    };
    socket.ws.onopen = function(event) {
        for (var i in messageQueue) {
            socket.ws.send(messageQueue[i]);
        }
        messageQueue = [];
        if (deferredCallback) {
            socket.ws.onmessage = deferredCallback;
            deferredCallback = null;
        }
    };
    return socket;
}]);

Implementation example in controllers:

app.controller('MainCtrl', ['$scope', 'socket', function($scope, socket) {
    socket.onmessage(function(event) {
        // Parse and process incoming event data
    });
}]);

app.controller('SearchCtrl', ['$scope', 'socket', function($scope, socket) {
    socket.send({
        // Data to be sent
    });
}]);

Answer №2

Be sure to check out this informative answer : Exploring AngularJS and the Realm of WebSockets

This example delves into the realm of creating a WebSocket service within AngularJS, showcasing its capabilities for handling request/response interactions as well as facilitating publish/subscribe functionality.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is my approach correct in utilizing hierarchical data structure for geospatial/geohash searching in firebase?

Objective: Develop a database of aerial photography. Data should be entered using AngularJS forms and retrieved using a map viewer like leaflet. Aims: Retrieve information in various ways: by Flight, Collection, Image by ID, and Image by Geography Da ...

What is the best way to transfer a JavaScript variable through a query string from one HTML page to another?

Is there a way to pass a JavaScript variable called username from one HTML page, example1.html, to another HTML page, example2.html, using query strings? <script type="text/javascript" > $(document).ready(function() { $('#SubmitForm ...

Resolve feature for UI routes fails to function upon refreshing the page

My app utilizes UI Route for view routing. When accessing /berlinerliste/, a function is triggered to display an array of objects. If one of these objects is clicked, the view changes to /berlinerliste/{id}/ and shows the details of that specific object. ...

Using React.useMemo does not efficiently avoid unnecessary re-renders

In my code, I am working with a simple component as shown below: const Dashboard = () => { const [{ data, loading, hasError, errors }] = useApiCall(true) if (hasError) { return null } return ( <Fragment> <ActivityFeedTi ...

Change the background of the play/stop icon with a jquery toggle

There is a list of video links with play icons as backgrounds in front of them. When a user clicks on a link, the video will start playing in a player located to the left of the links. The clicked link's background icon changes to a 'stop' i ...

Guide to displaying JSON.stringify data in PHP

I am attempting to retrieve my Google contact list using the Contact API. I have successfully retrieved the result and it is displaying in the console of both Chrome and Firefox browsers. However, I want to print this data using PHP on the same page. < ...

`Need help setting the active class for a bootstrap navbar using Angular JS?`

In my bootstrap navbar, I have the following menu items: Home | About | Contact I'm looking to assign the active class to each menu item based on the current angular route. Specifically, how can I set class="active" when the angular route is at # ...

How to Utilize Custom Component Tag Names in CSS with Vue.js 2?

<template> <header> <hamburger></hamburger> <app-title></app-title> <lives></lives> </header> </template> <script> export default { name: 'Titlebar& ...

What is the best way to modify the size of a canvas element while maintaining effectiveness?

I've encountered an issue while using Canvas to create a pie chart with chart.js. Despite adjusting the dimensions of the canvas element, it continues to take up the entire page. <canvas id="myChart" height ="200" width="200"></can ...

Exploring the functionality of Radar Chart within a React component

Within the index.html file that is being utilized, there exists a javascript code specifically designed for the chart function. <script src="js/plugins/chartJs/Chart.min.js"></script> var radarData = { labels: ["In Perso ...

Preventing horizontal swiping while vertically scrolling on mobile devices

How can I prevent horizontal swipe functionality from interfering with vertical scrolling on a webpage? I have successfully blocked vertical scrolling but need help finding a solution for preventing horizontal swiping. Has anyone else encountered this issu ...

What are the steps to utilizing the $document service in AngularJS?

I am a complete beginner when it comes to AngularJS and JavaScript in general, and I find myself a bit confused about the usage of $document. From what I understand, $document provides access to some JQuery functions. So, if I want to remove an element tha ...

Enhanced dropdown menu with Vue.js

Trying to manage two select lists where their combined values equal a maximum size. For example, if the max number of people is 20 and 5 children are selected, only a maximum of 15 adults can be added, and so on. My latest attempt: Template: <div cla ...

The absence of injection into the Angular view

I've been working on a simple Angular app and I recently added a router in my route.js file. However, for some reason the connection between mainCtrl and someview.html is not functioning correctly. This is evident because the view is not being injecte ...

Consistent outcomes with PHP AJAX

Currently in the process of verifying if the email is already being used (for a password reset). Here is the JavaScript code: //Verification of email existence $(document).ready(function() { //Listening for input in the email field $("#email").keyup(funct ...

Utilizing Array.from with a XPathResult: A Comprehensive Guide

In my sample document, I found 138 nodes with the tag td using querySelectorAll. Array.from(document.querySelectorAll('td')).length 138 However, when I tried to do the same using XPath, I did not get any result: Array.from(document.evaluate(". ...

Runtime Error: Invalid source property detected - Firebase and Next.js collaboration issue

Currently, I am developing a Next.js application that retrieves data from a Firestore database. The database connection has been successfully established, and the data is populating the app. However, I am facing an issue with displaying the image {marketpl ...

Is it possible to enhance a model's properties in AngularJS using a filter?

I need to format a timestamp in a unique way. For instance: Today at 4:57:30pm (coming up soon) Instead of using a filter to generate HTML, I would like to keep the HTML tags and classes within the template. Is there a way for the filter to add new prope ...

Animate CSS with Javascript in reverse direction

Forgive me if this is a silly question, but I'm having trouble. I need a slide-in navigation menu for smaller screens that is triggered by JavaScript. Here is what I currently have: HTML <nav class="responsive"> <ul class="nav-list unstyl ...

How to properly utilize ng-repeat and ng-switch in AngularJS?

Scenario: I have encountered multiple queries similar to mine, but I am struggling to find a solution to my specific question. In my code, I am working with an array of objects: $scope.messages = [obj1, obj2, ...]; Each object in the array follows this ...