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

Enhancing user engagement with PDF files using AngularJS to create an interactive and captivating page-turn

Anyone familiar with how to achieve a page turner effect for PDF files using Angular? I'm open to jQuery solutions as well. I've come across turn.js, which uses HTML, but I'm specifically looking for a way to implement this effect with PDF f ...

Is there a way to transform this JSON string into a particular format?

When moving a string from view to controller, I have encountered an issue. Below is the ajax code I am using: var formData = $('#spec-wip-form, #platingspec-form').serializeArray(); var platingId = @Model.PlatingId; var form = JSON.s ...

Utilizing the 'PUT' update technique within $resource

Hey there, I'm pretty new to Angular and looking for some guidance on how to implement a PUT update using angular $resource. I've been able to figure it out for all 'jobs' and one 'job', but I could use some assistance with in ...

Is it possible to enhance controllers in Sails.js through extension methods?

There are times when I need to execute a certain action on every page of my web application or make a specific method available to all controllers. Previously, in object-oriented MVC frameworks, I would have my controllers extend a base controller and de ...

Remove data from Firebase that is older than two hours

I need to implement a solution to automatically delete data that is older than two hours. Currently, I am iterating through all the data on the client-side and deleting outdated entries. However, this approach triggers the db.on('value') function ...

Merging Documents in PouchDB

I need to retrieve equipment data from pouchdb/couchbase that has users assigned to them. Each piece of equipment has an _id and a checkedOutBy field with the user._id as its value. The employee object contains the user's name. How can I retrieve the ...

Timeout error of 10000ms occurred while using await with Promise.all in Mocha unit tests

Document: index.ts // Default Exported Classes getItemsA() { return Promise.resolve({ // Simulating API call. Mocking for now. success: true, result: [{ itemA: [] }] }); } getItemsB() { return Promise.resolve({ // Simulating API cal ...

Is there a way to restore the face's original orientation after it has been rotated

Just to note, I am aware that this question has been asked before. However, the previous answers did not address my specific situation and requirements. Currently, I am developing a Rubik's cube using three.js. To achieve lifelike rotations, I am rot ...

Search a location database using the user's current coordinates

Currently, I am working on a project that involves a database containing locations specified by longitude and latitude. Upon loading the index page, my goal is to fetch the user's location and then identify every point within a certain distance radius ...

"Retrieving the most recent data within an ng-repeat directive using AngularJS

I am facing an issue with ng-repeat in my application. It successfully fetches values from the database and displays them in input text fields. However, when I update these values and click the save button, the updated values are not being saved. Can someo ...

Is there a way to determine if a click occurred outside of a div without relying on stopPropagation and target event?

My goal is to track multiple div elements and determine if a click occurs outside of any of these divs. I am looking for a solution that does not involve using stopPropagation or event.target as they have negative effects. Is there an alternative method to ...

How can one access a specific element by its id that is located within an ng-template in Angular 6?

I have a question regarding accessing a button element inside an ng-template tag using its id in the TypeScript file. How can I accomplish that without encountering undefined errors? This is what I have tried so far: HTML <ng-template #popup > ...

Importing a module directly from the umd distribution may yield a distinct outcome compared to importing it

Within my Vite/Vue3 application, I am importing two identical umd.js files: One is located at node_modules/foo/bar/dist/foobar.umd.js (imported with alias @foo = node_modules/@foo). The second .umd.js file can be found at <root dir>/foo/bar/dist/ ...

Having an issue where the Jquery clone function is only duplicating the content once. Looking to

I'm currently working on existing HTML table code. My goal is to copy the text from the 'th' header rows and paste them inside the corresponding td cells for each subsequent row. While I have successfully managed to copy the header row, it o ...

Sending data from a controller to a service in Angular

Currently, I'm facing an issue while attempting to transfer a parameter from a controller to a service in Angular. Let's start with the controller code snippet: angular.module('CityCtrl', []).controller('CityController',[&apo ...

having trouble with changing the button's background color via toggle

I've been experimenting with toggling the background color of a button, similar to how changing the margin works. For some reason, the margin toggles correctly but the button's color doesn't. <script> let myBtn = document.querySele ...

When Axios is disconnected, the sequence of events following a user's action is no longer dependent on when it is called after a button

I am working on a script that performs the following actions: Upon clicking a button, an encoded text is sent to an API for decoding. The decoded text is then used as a query for a Google search link that opens in a new tab. JAVASCRIPT // Summary: // ...

"The implementation of real-time data retrieval through Socket.io is currently not functioning as expected

As a beginner in mean-stack, I tried to implement real-time data following some instructions but encountered errors. Can someone guide me on how to correctly use socket.io? I have provided my code below for fetching users from mongodb, kindly review and co ...

Arrange objects in an array according to the order specified in another array

Here is my array of car makes: const makes = [ {id: "4", name: "Audi"}, {id: "5", name: "Bmw"}, {id: "6", name: "Porsche"}, {id: "31", name: "Seat"}, {id: "32", name: "Skoda"}, {id: "36", name: "Toyota"}, {id: "38", name: "Volkswagen"} ] Now, I want to o ...

JavaScript code to fetch data from a MySQL database

I am looking to dynamically retrieve data from a MySQL database using PHP in JavaScript variable. The current data is static and I want to make it dynamic by fetching it from the MySQL database without altering the format. Specifically, I need to extract ...