Angular tip: Implementing a waiting mechanism for promise resolution in a parent controller

I've been encountering an issue that I haven't been able to resolve despite searching for solutions.

Currently, I am attempting to share data between two Angular controllers in CoffeeScript:

angular.module('app').controller 'accountCtrl', ($scope, $state, accountFactory) ->

    Api.Account.get(token: $scope.current_user.account_id).$promise.then ((response) ->
        accountFactory.set(response)
        $scope.account = accountFactory.account
    )

angular.module('app').controller 'accountPaymentMethodsCtrl', ($scope, $state, Api, accountFactory) ->

    $scope.account = accountFactory.account
    $scope.displayedPaymentMethods = [].concat($scope.account.payment_methods)

The data is stored in a factory like this:

angular.module('app').factory 'accountFactory', ->

    account = {
        payment_methods: {}

        set: (account) ->
            @account = account
            @account.payment_methods = account.payment_methods
    }

    account

However, upon refreshing the page,

$scope.displayedPaymentMethods = [].concat($scope.account.payment_methods)

triggers an error message stating

"cannot read property 'payment_methods' of undefined"

This occurs because $scope.account in the parent controller has not been resolved yet. How can I ensure that this line and others execute only after $scope.account in the parent controller has been resolved?

Answer №1

To make it work, encapsulate the below API call within a function:

Api.Account.get(token: $scope.current_user.account_id).$promise.then ((response) ->
    accountFactory.set(response)
    $scope.account = accountFactory.account
)

In your accountPaymentMethodsCtrl, simply call this function and ensure you wait for the promise to be resolved just like you did in accountCtrl.

This approach should do the trick!

Cheers!

Answer №2

Keep track of your account details by utilizing 'local storage' or 'cookies' for easy access to the information

Answer №3

To ensure that the child controller waits for the parent controller when they are on different routes, you can utilize route resolve in AngularJS.

If the controllers are not on separate routes, my recommendation would be to create a factory to store the data and then access it from both controllers.

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

Trying to match an individual variable with every single value in a list

I recently created a script for a Google Sheet that involves taking user input and comparing it to values already on the spreadsheet. Within the function below, I captured the user's desired number using the variable voltReqed. My goal is to compare ...

Error: Unable to submit form with jQuery due to timeout issue - e[h] function not recognized

This question has surfaced on SO previously without any solution, maybe due to a different scenario Below is the form in question <form id="testSubmit" method="post" action="submit.php"> <!--The value of the following field will be collecte ...

Exploring the functionalities of using Script in Next.js 13

I want to include a vanilla JavaScript script in my next.js application like this: import Script from "next/script"; <Component {...pageProps} /> <Script id="raychat-widget" strategy="afterInteractive&quo ...

The ng-bootstrap datepicker does not allow setting a default date prior to selection

I have implemented the ng-bootstrap date picker in my project and I am facing an issue with setting a default date for the input field before selecting a date from the datepicker itself. <input type="text" id="datepicker{{i}}" class="form-control" form ...

Google-CDN maintains the CDN path and does not alter it, leaving it as is in the bower_components directory

I attempted to use the google-cdn plugin with Gulp (gulp-google-cdn) to replace bower references in my HTML file with the CDN equivalent. However, when I tried to run the plugin, it did not work and the DEBUG mode revealed the message: google-cdn Could not ...

CSS manipulation through JavaScript poses a challenge

My attempt to update a form is causing some issues. I have been conducting tests with the following elements: <span id="a">30 <span id="aa" style="display:none;"><input type="text" id="aa" name="q"/></span></span> <span id ...

How can I make my iPad switch to landscape mode in my specific situation?

I'm attempting to trigger the landscape mode on an iPad web browser, including the address bar and tabs, when a user clicks a link. Here's what I currently have: <div> <a ng-click="click me()" href="www.cnn.com">Click me</a&g ...

What is the proper way to utilize a variable as a field name in a Mongo query within the Meteor framework?

Is there a way to utilize a variable as a field name in a Mongo query within a Meteor application? For instance... This code snippet performs a find operation on my request controllers collection after capitalizing the collection name for the parent id o ...

Avoid having the state update repeatedly in Vue components after dispatching any updates

Stepping into the realm of Vue and Vuex, I find myself faced with a challenge. I am in the process of creating a customer list with multiple products. To make this possible, I have set up a customer array within my Vue component that includes a products ar ...

Regular expression to enclose non-quoted values (numbers and boolean) within quotes

I have a JSON file that is valid, but I need to add quotes around the number values and boolean values in order to send this JSON to a wix repeater that requires quotes around them. If anyone can assist me with this, I would greatly appreciate it. Exampl ...

Ways to extract information from a dynamically loaded webpage

Is there a way to extract data from a news website that automatically reloads at set time intervals? I want to use this data on my own website as information, whether it's in the form of images or text. Can anyone guide me on how to retrieve data from ...

Do external JavaScript files exclusively serve as repositories for functions?

Hey there, I'm a beginner in Web Development and I have a question that might sound silly: If I decide to keep my scripts in an external .js file, would it essentially just serve as a container for functions? For instance, if I attempt to include cod ...

Is Websocket support automatically provided in Node.js?

Conflicting information has left me puzzled. While reading the node docs yesterday, I was under the impression that Node's 'net' and 'http' modules had web socket capabilities. However, today I came across an article claiming that ...

What are some methods to alert my JS client without constant polling?

Situation: In my web application, I trigger a lengthy operation using JavaScript that runs on the .NET2.0 backend. The call returns quickly with an operation ID while the operation continues in the background. These operations don't require much CPU p ...

Issue with loading animated Three.js file causing it to not display correct

I created an animation in Blender and exported it as a Three.js file to incorporate it into my Three.js code. Below is the JavaScript code snippet: var loader = new THREE.JSONLoader(); loader.load( "obj/dog5.js", function( geometry ) { mesh = new THR ...

Retrieve the outer-HTML of an element when it is clicked

I am working on a project to develop a tool for locating xpath, and I am seeking the most efficient and user-friendly method for allowing the user to select the desired element on a webpage. Ideally, this selection should be made with just a single click, ...

Looking to display a div with a unique timer?

Is there a way to display different divs with unique classes for specific durations of time? For example, I want one div to show for 2000 ms with the class 'one', then another div to show for 4000 ms with the class 'two', followed by a ...

Is your Material UI Responsive Appbar overlapping the main content? Looking for a solution to address this issue?

Currently, I am in the process of developing a website that incorporates a responsive-based app bar with an attached drawer. The design concept I am following can be located at this link, which I have been modifying to suit my needs. However, I have encoun ...

The response body in Express is returned as a ReadableStream instead of the typical JSON format

When using Express to create an API endpoint, I typically respond with res.json() to send a JSON object in the response that can be consumed by the client. In my API, I am implementing batched promises, resolving them, and sending back an object. However ...

Ways to merge multiple functions into a single function in Vue.js

I want to create a single button that can turn on all the lights when clicked, but unfortunately, only two of the functions are being executed. <div><button v-on:click="onLightar(); onLightmngr(); onLightfy(); onLightmr(); onLightT(); o ...