Unable to store web service response in the $scope object

I'm facing an issue with setting the result when receiving a websocket message.
I have a controller that, upon clicking a button, triggers the getStops function.

Within this function (getStops), I utilize a websocket connection to receive messages
(at ws.onmessage), where I need to extract
tramState['stop_id'] and assign it to $scope.current_stop.

Subsequently, the corresponding li in the ul list should become active.
However, this is not happening as expected; $scope.current_stop always remains null.

Any insights on where the problem might be originating from? Appreciate any help.

angular.module('tramApp').
    controller('tramController', ['$scope', 'tramAPIService', function($scope, tramAPIService) {
        $scope.trams = [];
        $scope.stops = [];
        $scope.active_tram = null;
        $scope.current_stop = null;

    $scope.getStops = function (tram_id) {
        tramAPIService.getStops(tram_id)
            .then(stops => $scope.stops = stops);

        $scope.active_tram = tram_id;

        const ws = new WebSocket(`ws://192.168.0.103:8080/tram_ws/?tram_id=${tram_id}`);

        ws.onmessage = (message) => {
            let tramState = JSON.parse(JSON.parse(message.data));
            $scope.current_stop = (tramState['stop_id'] !== "None") ? Number(tramState['stop_id']) : null;
            console.log(tramState);
        };
    };

    tramAPIService.getTrams()
        .then(trams => $scope.trams = trams);

}]);  


<ul class="list-group">
      <li
          class="list-group-item"
          ng-repeat="s in stops"
          ng-class="{'active': s.stop_id === current_stop}">
          {{ s.stop_id }}, {{ s.stop_name }}
      </li>
</ul>

Answer №1

The issue lies in the fact that you are modifying an angular $scope variable from outside of the AngularJS environment. This means that AngularJS is not aware of these changes, resulting in them not being reflected in the user interface. The mechanism for updating bindings related to the $scope is known as the digest cycle system. In such cases, you need to manually trigger this process in order to see the updates on the screen.

There are two ways to trigger this process:

  1. By using the $apply method on the $scope
  2. Alternatively, you can utilize the $timeout and $applyAsync methods (which is the preferred approach)

    ws.onmessage = (message) => {
        let tramState = JSON.parse(JSON.parse(message.data));
        $scope.$applyAsync(function(){
           $scope.current_stop = (tramState['stop_id'] !== "None") ? Number(tramState['stop_id']) : null;
        });
    };
    

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

loop through the array of objects using ng-repeat in Angular

I am facing an issue where I need to display the data fetched from a service in my application. The service response is as follows: Object {resultado:array[2], mensaje: "4 personas `necesita tu ayuda"} Currently, the "resultado" field contains an object ...

Looking to locate an array within a schema using its unique identifier

const FormFieldsSchema = new Schema({ formName: { type: String, required: true }, fields: [ { fieldLabel: { type: String, required: true }, inputData: [{ type: mongoose.Schema.ObjectId, re ...

What is the best way to showcase a value in JavaScript using CSS styling?

I'm looking to customize the background, font style, and outline for both open and closed elements in the code snippet below: a.innerHTML = "We are Open now now."; a.innerHTML = "We are Closed, arm."; Additionally, I want to appl ...

Disappear scrollbar when overlay is activated

How can I hide the scroll bar when an overlay is displayed on my page? .overlay{ display: none; opacity:0.8; background-color:#ccc; position:fixed; width:100%; height:10 ...

Issue arises with asynchronous function outside of mounted lifecycle hook in VueJS

Identifying the Issue I encountered an issue while trying to create an external async function and assign its return value directly to a state variable. In addition, I passed firebase reference and store to this function to avoid importing them again in t ...

Modernize legacy Angular codebase to the most recent version (v15)

I'm trying to find the smoothest path to upgrading an angular application from v7 to v15. It's a big codebase with numerous deprecated packages and implementations. Is there a simpler approach to tackling this task? I appreciate any advice you ca ...

What steps can be taken to ensure a dropdown selection is required when a specific variable is true?

How can I create an AngularJS dropdown that requires a selection only when a specific variable, such as 'x', is set to true? If 'x' is false, it should allow saving without a selection. Below is the code for my dropdown: <select cla ...

"Switching a div's visibility when a link is clicked

http://jsfiddle.net/FsCHJ/2/ Currently, when I add another link, it automatically uses the same functionality as the toggle button. What I want is for "Toggle Edit Mode" to toggle a hidden div on and off. I attempted to modify the code from $("a").click(f ...

The ng-show directive is failing to update properly after changes are made to the scope values

I'm experiencing some issues with the ng-show method. I have set it up like this: Even though the username string length is checked, the ng-show method doesn't seem to hide/show the extra text until after another keystroke. How can I make it upd ...

How to automatically embed a p5.js canvas into an HTML canvas with the drawImage() method

Whenever I attempt to draw the p5.js canvas into an HTML canvas using drawImage(), I always encounter this error: Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type ' ...

Adding a new path to the end of an existing path using Ui-router

For my oAuth website, users will initially land on the /core/login path. However, I've noticed that when state changes occur from this page, the URLs are being appended to it. For example, if a user accesses the Reset Password feature with a state URL ...

Tips for extracting the index of the chosen item from a dropdown using ReactJs and Material UI

This is the code snippet for Dropdown component implementation: <DropDownField name={formElement.name} label={formElement.name} value={formik.values[formElement.name] || ''} dropDownItems={formElement.name === &apo ...

There was a problem establishing a WebSocket connection to 'ws://127.0.0.1:2000/'. The attempt failed with the following error: net::ERR_CONNECTION_REFUSED

I have integrated websocket functionality using a repository found at https://github.com/kishor10d/CodeIgniter-Ratchet-Websocket After successfully testing the websocket on my local environment, I encountered issues when uploading the files to the live se ...

Data filtration - techniques for removing unnecessary information in JavaScript

I have a JSON file containing data that requires filtering. Here is an example structure of the JSON: [{A:"data", C:"flightData", D:"FlightData"}, {B:"data", C:"flightData", D:"FlightData"}, {A:"data", C:"flightData", D:"FlightData"}, {B:"data", C:"flig ...

Issue with jQuery Ajax file upload in CodeIgniter

I am attempting to use AJAX to upload a file in the CodeIgniter framework, but I encountered an error message stating 'You did not select a file to upload.' Please review this code: View <form method="POST" action="" enctype="multipart/form- ...

Storing user input from Vue.js in a JavaScript array for future use

Utilizing vue.js <template> <input id="email" v-model="email" type="text" placeholder="Email"> <input id="name" v-model="name" type="text" placeholder=" ...

Is it possible to define a shared function for enums in TypeScript?

I have created an enumeration called VideoCategoryEnum: enum VideoCategoryEnum { knowledge = 0, condition = 1, interview = 2, speech = 3, entertainment = 4, news = 5, advertisement = 6, others = 7, } I am looking to implement a shared met ...

Exploring the Functionality of Drag and Drop with JPG and GIF in Internet Explorer 9/10/11

When trying to drag, drop, or select a file using a form in Internet Explorer 9/10/11, only JPEG and PNG files are accepted, while JPG and GIF extensions are rejected. This issue is present in both the code I am using below and in the demo found at https:/ ...

What steps can be taken to avoid including empty tasks in React code?

Is there a way to prevent my application from adding empty tasks? Below is the code snippet for adding a new task to an array. How can I implement a condition to block the addition of empty tasks? This application follows Mozilla's guidelines for a R ...

Using TypeScript controllers to inject $scope

Currently, I am in the process of creating my initial typescript controller and encountering a slight challenge in comprehending how to utilize $scope effectively in order to reference elements within various code blocks. Below is the relevant snippet of c ...