Accessing AngularJS variable scope outside of a function

Utilizing a socket, I am fetching data into an angularJS controller.

$rootScope.list1= '';
socket.emit('ticker', symbol);
socket.on('quote', function(data) {
    $rootScope.list1 = angular.fromJson(data.substring(3));
//I can't call any function from here to use this variable
});

I am trying to access the updated list1 variable in the code below, but its value remains '' due to it being accessed before being updated - prior to receiving the response.

Is there a method to utilize the updated value of the list1 variable in the following code?

Edit 1

Following the recommendation from @Manish Singh in one of the responses, I attempted using $rootScope.watch. It successfully reflects the new value for the above code snippet but not for the subsequent code provided below.

$rootScope.peers = [];
industrysearch.searchindustry(indussymbol).then(function(results) {
  industrysearch.searchpeers($scope.industrystock[0]._source.industry).then(function(results1) {
            for (var number_stocks = 0; number_stocks < results1.length; number_stocks++) {
                $rootScope.peers.push(results1[number_stocks]);
            }
        });
    });
    $rootScope.$watch('peers', function(newVal1, oldVal1) {
      console.log(newVal1); //prints []
    });

The only difference seems to be that one is a normal variable and the other is used as an array.

Edit 2

I missed using $watchCollection for arrays/collections. The following code is now functional.

$rootScope.$watchCollection('peers', function(newVal1, oldVal1) {
      console.log(newVal1);
    }); 

Thank you for the assistance!

Answer №1

Why not utilize a timepiece in $rootScope

$rootScope.$watch('list1', function(newVal, oldVal) {
//Execute some action
)};

Answer №2

Experiment with "$applyAsync":

$rootScope.data= '';
socket.emit('request', symbol);
socket.on('dataUpdate', function(data) {
    $rootScope.$applyAsync(function(){
       $rootScope.data = angular.fromJson(data.substring(3));
    });
});

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

retrieving information from server via ajax to display on chart

I am currently utilizing the jqPlot JavaScript library for generating graphs and charts in one of my applications, which can be found at . Within my application, there are approximately 5-6 pages where I have integrated this library. However, I would like ...

Uncaught ReferenceError: jQuery is undefined" - Navigating the Angular and JavaScript Realm with

There is an Angular project that I am working on, and it utilizes the AvayaClientSDK consisting of three JavaScript files. While trying to import the AvayaClientSDK JS file into my component, an error message stating "jQuery is not defined" appeared. ...

Send the values of the form variables as arguments

I am trying to integrate a webform (shown below) with a function that passes form variables. Once the user clicks submit, I want the username and password to be passed into a website login function: $.ajax( { url: "http://microsubs.risk.ne ...

Preventing page reload in Supabase with NextJS when the website loses focus and regains it

I am working with the structure in _app.js of my Next.js app. // _app.js // import ... import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs' import { SessionContextProvider } from '@supabase/auth-helpers-react' // ...

Adding a CSS class to an HTML element using JQuery

I have a collection of tabs, and I want to dynamically add an <hr> element with the class "break-sec" when a certain class is active. This element should be placed within a <span> element with the class "vc_tta-title-text" after the text. Here ...

What is the reason behind Google Closure Compiler appending a variable to the global namespace when the original namespace was blank?

My long script is neatly enclosed within a (function() {/.../})() to prevent any name pollution. It has been typed with complete accuracy and zero warnings. I recently discovered that Google Closure compiler initially redefines i and j in the global names ...

In search of assistance with a persistent react.js error plaguing my work

I keep encountering an error whenever I run npm start on a new project. Does anyone have any insight on how to resolve this issue? The problem might lie within the project dependency tree rather than being a bug in Create React App. Here is what you can ...

Multi-line input in ExtJs

Is there a way to create a multiline input with vertical scrollbars in EXTJS? I tried the following code: noteField = new Ext.form.TextField({ emptyText: 'note...', multiline: true, applyTo: &apos ...

What is the best way to eliminate the default hover effect using the MenuItem Mui class?

My goal is to eliminate the default gray hover over animation when using the MUI menu item class. I have attempted several methods, but none have been successful so far. Here are a couple of examples: <MenuItem divider sx={{'&:hover':{bac ...

retrieve the height value of a div element using AngularJS

I'm having trouble retrieving the updated height of a div using AngularJS. It seems to only provide the initial value and does not update as expected: vm.summaryHeight = $(".history-log-container").height(); console.log(vm.summaryHeight);//always dis ...

Tips for manipulating specific URL redirection to an alternative URL within a NuxtJs application

Take this scenario, where the inputted URL is: http://localhost:3000/course-details The desired outcome should be a redirection to http://localhost:3000/courses I recall there being a method for achieving this, but it slips my mind at the moment. ...

AngularJS initiates an XMLHttpRequest (XHR) request before each routeChange, without being dependent on the controller being used

I'm currently embarking on a new project, and for the initial phase, I want to verify if the user has an active session with the server by sending an XHR HEAD request to /api/me. My objective is to implement the following syntax $rootScope.$on("$rou ...

Using an object does not result in updated data, while data changes are typically observed when using a variable

In the process of developing a function to update a custom checkbox upon clicking (without resorting to using the native checkbox for specific reasons). Here's the code snippet for the checkbox: <div class="tick-box" :class="{ tick: isTicked }" @ ...

Adding DOM elements dynamically from a controller in Angular.js is a powerful feature that

Hey there, I'm just getting started with Angular and may not be using the best practices yet. One thing I'm working on is appending a <circle> element within the controller function called placeShot(), which is triggered by ng-click='p ...

Is it possible to create a compound editor within a cell in SlickGrid that contains two date fields

Currently, I am implementing SlickGrid with jQuery and I am interested in incorporating a compound editor within a cell similar to example 3a mentioned here. However, instead of two text fields, I would like to have two date fields. Although Example 3 dem ...

Displaying React components for a brief duration of time

I have an existing React component where I need to display another component for a specific duration. Upon mounting or data loading of the parent component, the child component should become visible after 1-2 seconds and then disappear after a few more sec ...

Cannot access a Typescript method variable within an inline function

I've encountered an issue with my code involving loading values into the array usageCategory within an inline function. Despite successfully adding values to the array inside the function, I am unable to print them outside it. getAllUsageCategoryElem ...

Trigger the script upon clicking the Save button within the AdminBro Edit page

AdminBro's documentation mentions that they provide predefined actions Edit (record action) - update records in a resource They also offer a hook called after. I created a function and assigned it to MyResource.edit.after. However, the issue is tha ...

The life cycle of the request/response object in Express.js when using callbacks

Feel free to correct me if this question has already been asked. (I've done as much research as I can handle before asking) I'm really trying to wrap my head around the life cycle of request and response objects. Take a look at the following co ...

Clicking on multiple instances of the same Vue.js component (popover) results in displaying identical data

Attempting to display an AJAX response in a popover shown by clicking an icon (a custom Vue component) brings about a challenge. The issue arises when there are multiple instances of this component, dynamically rendered through the v-for directive within a ...