Unable to update variable values in event listener function in $rootScope

In my controller, I am utilizing $rootScope.$on to monitor an event emitted by a module called angular-packery. The event is successfully captured and I can manipulate the 'args'. However, my goal is to store the args object in a variable declared outside the listener function's scope. I have attempted the following code:

(function() {
    'use strict';
    angular
        .module('app')
        .controller('searchSpeakersResultsCtrl', searchSpeakersResultsCtrl);

        searchSpeakersResultsCtrl.$inject = ['$rootScope', '$scope'];
        function searchSpeakersResultsCtrl($rootScope, $scope) {
            var vm = $scope;

            var pckry = {};
            var packeryEventListener = function (event, args) {
                pckry = args;
                console.log(pckry);
            }

            var unbind = $rootScope.$on('packeryInstantiated', packeryEventListener);
            console.log(pckry);
            vm.$on('$destroy', unbind);

        }
})();

The value of 'pckry' remains empty when logged outside the listener function, despite showing the correct value within the function.

Interestingly, if I call the packeryEventListener function directly instead of through $rootScope.$on, the value of 'pckry' is updated as expected outside the function.

It appears that there might be an issue with JavaScript variable scope when used in conjunction with $rootScope.$on. Any insights on what might be causing this behavior would be greatly appreciated. Thank you! - H.

Answer №1

The issue you're facing here boils down to timing: the console.log is triggered before the callback has a chance to populate the variable, resulting in an empty object being displayed. It's important to keep in mind that Angular operates in an asynchronous environment, meaning that callbacks often occur later than anticipated.

In order to address this issue, consider encapsulating the code within a $timeout(). However, it's generally advisable to ensure that any code reliant on an asynchronous operation does not execute until said operation has been completed. This typically involves utilizing promises, which allow actions to be performed upon resolution (using .then()) or rejection (using .catch()). Additionally, promises can be combined using methods like $q.all() to wait for multiple operations to finish.

It's worth noting that both $timeout and $http also return promises.

Furthermore, even if a promise resolved some time ago, you can always use

thePromise.then(function() {...})
as a safeguard to execute specific code after the promise has resolved. Keep in mind that the callback will still run asynchronously, so it won't occur until after your other code has finished executing.

Answer №2

Yes, make sure to store the value in $scope and then proceed with something similar to this:

(function() {
'use strict';
angular
    .module('app')
    .controller('searchSpeakersResultsCtrl', searchSpeakersResultsCtrl);

    searchSpeakersResultsCtrl.$inject = ['$rootScope', '$scope'];
    function searchSpeakersResultsCtrl($rootScope, $scope) {
        var vm = $scope;

        var pckry = {};
        var packeryEventListener = function (event, args) {
            $scope.pckry = args;
            console.log($scope.pckry);
        }

        var unbind = $rootScope.$on('packeryInstantiated', packeryEventListener);
        console.log($scope.pckry);
        vm.$on('$destroy', unbind);

    }
})();

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

Screenshots of playwright failing to work on Github.''

Within my playwright.config.ts file, I have specified the following: use: { ... screenshot: 'only-on-failure', } When running tests locally and they fail, screenshots are successfully saved in /test-results. However, the issue arises when th ...

Is it possible for jQuery ajax to still work properly even when $ is not defined?

Firebug is pointing out an error that says "$ is not defined (70 out of range 28)" Even though the code is running smoothly, I am puzzled by this. The code searches for a div with the class "like" and when clicked, sends values to ajax. Here's the re ...

Configuring the baseUrl for Axios in a Vue.js application triggers the sending of a request

I have encountered an issue in my app where Axios automatically makes a request to the baseUrl without me explicitly making one. This occurs even when the app is loaded in the browser. In my main.js file, I have set the baseUrl using: axios.defaults.baseU ...

When attempting to decrypt with a password using CryptoJS, AES decryption returns an empty result

Example The code snippet below is what I am currently using: <script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script> <div id="decrypted">Please wait...</div> Insert new note:<input type="te ...

JavaScript encountering issues when parsing a string that was serialized using Gson in Java

This question is unique and differs from this one as it specifically addresses the representation of JSON strings serialized from Java in literal form in JavaScript, with a focus beyond just double quotes. In my scenario, I am serializing a JSON object in ...

Error encountered in React caused by axios get request as data is undefined

Struggling to retrieve data from a MongoDB collection, the process goes smoothly in Insomnia, but I encounter an error when making a request with axios: Uncaught TypeError: Cannot read properties of undefined (reading 'games') Utilizing a custom ...

Using arrow functions in node.js

Can someone help me understand how arrow functions work? I know that arrow functions are typed like this () =>, but I'm curious about how the function that contains the arrow function knows how to call it. For example: app.listen(3000 , () => ...

Four unique chip/tag colors, personalized to suit your style

Currently, I have integrated two arrays into my autocomplete menu where the chip/tag color is either primary or secondary based on the array the selected component belongs to. I aim to include all four arrays in the menu (top10Songs, top10Artists, top10Fi ...

Uncovering the enum object value by passing a key in typescript/javascript

How can I retrieve the value of an enum object by passing the key in typescript? The switch case method works, but what if the enum object is too long? Is there a better way to achieve this? export enum AllGroup = { 'GROUP_AUS': 'A' &a ...

Issue: The variable '$viewMap[...]' is either null or undefined

Unfortunately, my knowledge of jQuery/Javascript is quite limited. I am encountering a Javascript error when trying to change the "how did you hear about us" dropdown on a form. The error message states: Error: '$viewMap[...]' is null or not an ...

JSON parsing error: an unexpected token was encountered

I have recently validated the JSON string response on this JSON formatter tool and it confirms that the JSON string is valid. Below is the function I utilized to serialize data into a JSON string: private string getJSONData() { obj_userSession = new ...

The Javascript style.opacity function eliminates the leading zero from the input string

In my application, users have the ability to change the color of the background but not the pattern. They can adjust the background behind the pattern and the opacity of the pattern. Users are prompted to input a percentage, which is actually a number betw ...

After deploying a Next.js project on an Ubuntu server, dynamic pages are returning a 404 error

I've been putting in a substantial amount of time on this project. I'm encountering some 404 errors on my dynamic pages, even though they work perfectly fine on localhost. I've tried using revalidate and playing around with fallback: true an ...

Using Angular to pass an attribute into a directive and utilizing it as a property name on an object

Is it possible to utilize the checkType attribute in a way that resolves as scope.countFrom = sseHandler.broadcastStamp[checkType];? I am attempting to do this in order to easily input the value and create a reusable directive. Currently, I am encounterin ...

Uploading files with a progress bar in NodeJS by utilizing Core NodeJS and the authentic Node approach

Ryan Dahl mentioned that he created NodeJS to address the file upload progress bar issue (https://youtu.be/SAc0vQCC6UQ). During its introduction in 2009, Node utilized technology available at the time before more advanced client-side javascript libraries l ...

Why does the click event on a dynamically created checkbox in a jQuery datatable select the entire row instead of just the checkbox itself?

I have recently made an update to my jquery datatable where I included a new row with HTML content (a checkbox input) based on a specific event: $("#btn").on( 'click', function (){ $('#mytable').DataTable().row.add([data[0],data[1] ...

Apply a specific class to the input field when the name matches x

I have a website that loads a JavaScript file from a commercial service, so I am unable to customize this file. The output of this JavaScript file is a form with various input fields, all of which have the class name "wf-input". I now want to add a jQuery ...

A function that receives another function as a parameter

I need assistance in defining a function that can call another function passed as a parameter within the main function. function displayMessage(title, message, button, callback) { console.log(title, message, button); if (typeof(callback) !== "f ...

Tips for identifying when a tab has been reopened following closure?

There seems to be a problem with the JS state where it changes but then reverts back to its original state when the tab is closed and restored using cmd/ctrl + shift + t. Typically, data is fetched from the server via ajax using Vue's mounted() lifec ...

Tracking changes in local storage through mapped React components

I'm currently working on implementing a cart feature, where I've already set up the cart in local storage using JSON. However, I'm facing an issue when trying to allow users to adjust the quantity of each product in the cart. The handleItem ...