AngularJS - Unusual outcomes observed while utilizing $watch on a variable from an external AngularJS service

Within the constructor of my controllers, I execute the following function:

  constructor(private $scope, private $log : ng.ILogService, private lobbyStorage, private socketService) {
  this.init();
}

private init(){
  this.lobbyData = [];
  this.initializeLobbyData();

  // Initialization related to the DOM
  this.chatWindow = $('.chat-output');

  var self = this;
  this.$scope.$watch(
    function () {
      return self.socketService.chatHistory
    },
    function (newValue, oldValue) {
      if(typeof newValue.body !== "undefined" &&  newValue.body.data.length > 0){
        // Clear existing records
        self.chatWindow.empty();

        for (var i = 0; i < newValue.body.data.length; ++i) {
          console.log(newValue.body.data[i].body.userName)
          self.chatWindow.append($('<span><strong>' +  newValue.body.data[i].body.userName + '</strong> ' +  newValue.body.data[i].body.message + '<br></span>'));
        }
      }

    }
  );

  this.socketService.setUpWebsocketService();

}

This function is designed to monitor an external variable from an AngularJS Service that utilizes websocket.

During debugging in the browser (Chrome), the callback function of the $watcher gets triggered twice and ultimately populates the data into the chatWindow.

https://i.stack.imgur.com/6ChRO.png

However, when I run the web app without the debugger, the data fails to load.

https://i.stack.imgur.com/89v32.png

In order for the data to display in the chatWindow, I need to interact with the page by clicking a button or link. Strangely, any form of interaction (e.g., button, anchor) on the page triggers the data loading.

https://i.stack.imgur.com/rbie8.png

This behavior does not occur when I am actively debugging in the window. The data loads automatically without any user interaction required.

Can anyone offer an explanation for this phenomenon?

Answer №1

The reason for this behavior is that $watch only executes during the digest cycle, which occurs after $scope.$apply() is triggered by an event. Angular automatically handles this process when an ng-click event occurs, but your websocket library may not. In such cases, you need to manually call $scope.$apply() every time a response is received through the websocket.

For more information, refer to AngularJS' documentation on $scope.

On a side note: be cautious, as your

$('<span>'... + someUserName)
line could potentially pose a XSS vulnerability in your service, allowing users to inject malicious code such as script tags via chat messages.

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 it possible to refresh HTML content using jQuery?

Currently, I am attempting to iterate through response data and integrate the values into the HTML of my webpage. It's crucial for me to clear any existing values in the HTML so that only the new ones are displayed, keeping it up-to-date. The structu ...

Processing the results from a recursive function call in Node.js

I have an objects array that needs to be processed with delayed calls to an external server, then collect all results into an array for postprocessing. Here is an example: (async () => { const serverOperation = () => new Promise(resolve => setT ...

Getting data from a response in Express.js involves using the built-in methods provided by

I am a beginner at Node.js and I'm currently experimenting with client-server communication. Below are the codes I've been working on: server: app.post('/zsa', (req, res) => { res.send("zsamo"); }); client: fetch(&qu ...

Clicking on the React Bootstrap Checkbox within the Nav component does not trigger a rerender of the NavItem component

Encountering an unusual issue while using a Nav and NavItem with a Checkbox from React Bootstrap. What I've noticed is that when clicking directly on the checkbox instead of the NavItem button, the checkbox does not re-render correctly even though my ...

Jasmine encountered an error while trying to compare the same string: 'Expected the values to match.'

I'm encountering an error message, despite verifying that the strings are identical: Expected { $$state : { status : 1, value : { customerNumber : 'customerNumber', name : 'name', userId : 'buId', customerType : 'ty ...

Mastering Meteor: Techniques for Manipulating Mongodb Data in Real Time Display

Within my Meteor application, I have accomplished the successful publication of data from the server and its subscription on the client side. Instead of directly displaying raw data on the client's screen, I am interested in performing some calculatio ...

Rendering v-html in VueJS requires a delayed binding value that can only be triggered by clicking inside and outside of a textarea control

I'm currently experiencing an issue with a textarea that is bound to a v-model with a specific value. The problem arises when the content of the textarea is changed via JavaScript - the displayed value, represented by {{{value}}}, doesn't update ...

Leveraging the Google Feed API using jQuery's AJAX functionality

Currently, I am attempting to utilize Google's Feed API in order to load an RSS feed that returns a JSON string. (For more information, please refer to: https://developers.google.com/feed/). Despite this, my approach involves using jQuery's AJ ...

Creating a dynamic union type in Typescript based on the same interface properties

Is it possible to create a union type from siblings of the same interface? For example: interface Foo { values: string[]; defaultValue: string; } function fooo({values, defaultValue}: Foo) {} fooo({values: ['a', 'b'], defaultVal ...

jQuery does not allow for text input values to be posted

Having an issue with a form using the POST method. I have some PHP controls that are being calculated in jQuery. While all the form control values are accessible in the next form using POST, the values added through jQuery are not posting to the next form. ...

An error occurred while attempting to run the npm installation command

When trying to run the npm install command, I keep encountering this error: npm ERR! code 1 npm ERR! path /Users/alex/Documents/serviceName/node_modules/platform-tracer/node_modules/ls-trace npm ERR! command failed npm ERR! command sh -c node scripts/post_ ...

Check if the element is located on the active tab using jQuery

I have implemented a tab system to organize a lengthy form with multiple input fields. The form consists of 4 tabs, and beneath them, there is a preview section displaying the user's selections. In this preview area, I added icons that enable users ...

Use the keyboard to interact with the user interface

Imagine you have the following HTML markup - <ul id="list"> <li class="list-item" tabindex="0">test 1</li> <li class="list-item" tabindex="1">test 2</li> <li class="list-item" tabindex="2">test 3</li> ...

The javascript file is unable to detect the presence of the other file

I am facing an issue with two JavaScript files I have. The first one contains Vue code, while the other one includes a data array where I created the 'Feed' array. However, when trying to output a simple string from that array, the console throws ...

The React Nested Loop Query: Maximizing Efficiency in Data

Learning React has been a challenge for me, especially when comparing it to XML/XPath. In this scenario, I have two arrays simplified with basic string properties... customerList: Customer[] export class Customer { id: string = ""; firstnam ...

The Angular Node server is responding with the error message "You have entered 'undefined' instead of a stream."

Using angular 9 + universal has been smooth sailing until I encountered an issue after building the app with npm run build:ssr and attempting to run it using node: node dist/app/server/main.js. The error message that popped up in the terminal was: Node ...

Having trouble getting Ajax to function properly with CodeIgniter

Here is the AJAX code snippet: $.ajax({ url: '<?php echo base_url(); ?>deleteRowUsingApiKey/index', //This is the current doc type: "POST", //dataType:'json', // add json datatype to get json data: {name ...

Cannot access Injectable service in Angular2

In the angular2 application, there is a service named HttpClient. The purpose of this service is to include an authorization header in every request sent by the application to endpoints. import { Injectable } from '@angular/core'; import { He ...

React is nowhere to be seen

index.js: import react from 'react'; import {render} from 'react-dom'; render( <h1>Hello World!</h1>, document.getElementById('root') ); package.json: { "name": "", "version": "1.0.0", "descriptio ...

Issue: Incorrect parameters for executing the MySQL statement

Currently, I am working on a nodeJs project and utilizing the npm package mysql2 for connecting to a MySQL database. This is how my MySql Configuration looks like:- let mysql = MYSQL.createConnection({ host: `${config.mysql.host}`, user: `${config.mys ...