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

The Next.js website displays a favicon in Chrome, but it does not appear in Brave browser

As I work on my debut next.js website, I am configuring the favicon in index.js like this: <Head> <title>Create Next App</title> <link rel="icon" href="/favicon.ico" /> </Head> Initially, all my source ...

Is there a tool in Node.js to set up a new project, similar to the scaffolding feature in Visual Studio for C# projects

Is there a way to efficiently create a node.js project with TypeScript and Express, and embed an SPA client using React and Redux templates written in TypeScript as well? Is there a scaffolding tool available to streamline this process, similar to the ea ...

Auth0 Angular - No routes found to match

I recently set up an angular application and integrated it with Auth0 by following two helpful tutorials: https://auth0.com/docs/quickstart/spa/angular2/01-login https://auth0.com/docs/quickstart/spa/angular2/02-calling-an-api Here is a brief overview o ...

ES6 AngularJS 1: The Power of $inject and Inheritance

I am facing a situation where I have 3 child controllers that extend a shared parent controller. The structure looks like this: class ParentController { constructor( $scope, $state ){ this.$scope = $scope; this.$state = $state; } } ...

Pass the $scope object from a controller to a modal controller

I am facing an issue with transferring the $scope variable from ctrlone to ctrltwo, which is a modal window on my page. When I open the modal in ctrlone, my code looks like this: var modalInstance = $modal.open({ templateUrl: 'Modal.html&ap ...

Using Mootools to call a class function from a bound CSS class may lead to an error stating that it is not a function

Utilizing Mootools 1.3.2 Here is the code snippet: var DNReportAbuse = new Class({ Extends: DNUserDialog, comment_id: null, container: null, initialize: function(classname) { var bindclass = $(document.body).getElements(classname); bindclass. ...

What is another option for toggling in jQuery?

After deprecating the toggle method, I found a new way to toggle div: $("#syndicates_showmore").on("click", function () { if (!clicked) { $('#syndicates').fadeTo('slow', 0.3, function () { $(this).css( ...

When encountering error code EINTEGRITY during npm installation, a warning about a potentially corrupted tarball may be displayed

I have been facing an issue for the last three days with my react+vite project on Windows 10. Whenever I attempt to install dependencies using npm install, I encounter the following error: npm WARN tarball tarball data for fast-levenshtein@https://registry ...

Angular Material Popup - Interactive Map from AGM

I am in the process of developing a material dialog to collect user location information using AGM (angular google maps). I have successfully implemented a map on my main page, but when the dialog is opened, it only shows a blank space instead of the map. ...

"When testing with an API client, NextJS 13 successfully returns a response, however, the same response

Having trouble getting a clear answer on something really simple. I've created an API route: // /api/test/route.js export async function GET(request, response) { console.log("requested"); return NextResponse.json({ my: "data" ...

Using jQuery and regex to only allow alphanumeric characters, excluding symbols and spaces

Seeking advice, I am using a jquery function called alphanumers var alphanumers = /^[a-zA-Z0-9- ]*$/; which currently does not allow all symbols. However, I now wish to disallow the space character as well. Any suggestions? ...

Chrome showing random 0 status for $http and $ajax requests

Occasionally, an issue arises on the website where the browser starts returning status 0 for XMLHTTPRequest requests randomly. This problem applies to requests made through both the jquery ajax function and the $http resource in angularJS. Curiously, the ...

Chakra UI - The "Open Modal" button is disabled from being clicked repeatedly

Encountering an issue with Chakra UI modal dialog in Next.js. Attempting to utilize the code below in pages/index.tsx for displaying a modal dialog. import type { NextPage } from "next"; import { Modal, ModalOverlay, ModalContent, Moda ...

Monitoring inbound and outbound traffic in express middleware

I am in the process of incorporating a logger into my Express application. This logger needs to record both requests and responses (including status codes and body content) for each request made. My initial approach involves creating a middleware function ...

Trouble getting ng-change and ng-checked to function simultaneously with radio buttons in AngularJS

Visit this link for the code Here is a piece of Javascript code: angular.module("sampleapp", []).controller('samplecontroller', function($scope,$rootScope) { $scope.radii = [ {id:.25, checked:false, name:"1/4 Mile"}, {id:.5, checked:f ...

Node.js and Express facing challenge with Stripe checkout functionality

I am encountering an issue while attempting to integrate stripe into my checkout process. When I click on the checkout button, instead of being directed to the checkout page, I receive the following message: {"url":"https://checkout.stripe.c ...

The execution of 'observe' on 'MutationObserver' failed because parameter 1 is not the correct type of 'Node'. Ensure to use select2() instead

Attempting to implement select2 for dynamically loaded data via ajax, I am encountering the error mentioned above. What could be the issue? Below is the code snippet in question: $(document).on('change', '[name="country"]', fu ...

Unexpected symbol in JSON parsing with JavaScript

let information; $.ajax({ url: link, type: 'POST', dataType: "json", success: function (data, textStatus) { information = data; alert(data.name); } }); I am attempting to retrieve JSON-encoded data from a spe ...

We encountered a ReferenceError stating that 'dc' is not defined, despite having already imported d3, dc, and crossfilter in

In my current angular project, I have included the necessary imports in the component.ts file in the specific order of d3, crossfilter2, dc, and leaflet. Additionally, I have added the cdn for dc-leaflet.js in the index.html file. Despite these steps, wh ...

Obtain asynchronous result from updating state in React

I am trying to achieve the following: myFunction = () => { this.setState( state => { const originalBar = state.bar; return { foo: "bar" }; }, () => ({ originalBar, newBar: state.foo }) //return this object ...