Setting asynchronous value to controller variable in AngularJS

Upon receiving data from a remote request via companiesData.getCompanies(), I store it in a variable within the controller.

The issue arises when the controller proceeds without waiting for the promise to be resolved, resulting in an empty response array.

JS controller :

angular.module('X.Exh', [])

.controller('ExhibitorsController', function($scope, $state, $stateParams, companiesData) {

    this.companies = [];

    companiesData.getCompanies().then(function(response) {
        this.companies = response.data;
console.log(this.companies); // functioning properly
    });
});

HTML:

 <ion-alpha-scroll ng-model="Exh.companies" key="name" display-key="name" subheader="true" use-complete-alphabet="true">
<!-- The ion alpha scroll essentially performs an ng-repeat for each item, with no issues arising here -->

As the HTTP request is not waited upon, Exh.companies remains empty. (Note that if I omit this.companies = []; at the beginning of my controller, my HTML reports that Exh.companies is undefined.)

What is the appropriate method to fetch and handle the data effectively?

Answer №1

The content within the anonymous function has no impact on the original list of this.companies:

angular
 .module('X.Exh', [])
 .controller('ExhibitorsController', function($scope, $state, $stateParams, companiesData) {

    var vm = this;
    vm.companies = []; // You can exclude this line, but for clarity and documentation purposes, it's recommended to declare it.

    companiesData.getCompanies().then(function(response) {
        vm.companies = response.data;
        console.log(vm.companies); // This refers to the context in which the caller is located, not the local this.companies.
    });
});

Please keep in mind that vm. is utilized when implementing the controllerAs pattern.

Alternatively, you can directly access the $scope variable:

angular
 .module('X.Exh', [])
 .controller('ExhibitorsController', function($scope, $state, $stateParams, companiesData) {

    $scope.companies = []; // You can skip this line, but it's good practice for code clarity and documentation.

    companiesData.getCompanies().then(function(response) {
        $scope.companies = response.data;
        console.log($scope.companies); // Similar to above, this references the context of the caller, not the local this.companies.
    });
});

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

Manipulating object properties within an array through iteration

Here is the array I am working with: var data = [ {"firstname":"A","middlename":"B","lastname":"C"}, {"firstname":"L","middlename":"M","lastname":"N"}, {"firstname":"X","middlename":"Y","lastname":"Z"} ]; I need to update the values for all keys - firstn ...

What are the steps for implementing TextfieldProps from Material UI Props in a React Application?

Looking to create a custom single component TextInput for login using Material UI's Textfield with unique props? Wondering how to implement this using Textfieldprops from Material UI? Check out the code snippet below for the TextInput.tsx file: impo ...

Searching for data across multiple tables using the Laravel framework combined with Vue.js and API integration

I am currently implementing a multi-search feature for a single table The search functionality is functioning correctly but only for one column Here is the snippet from my controller: public function index() { return Matter::when(request('sear ...

Monitoring the setup file in a node.js environment

Currently, the node-config npm package is being utilized to manage the configuration of node.js. An obstacle I am facing is the need to monitor the file being used by node-config. Unfortunately, it appears that the capability to watch files has been remov ...

"The new Protractor 2.0 version does not seem to be incorporating a wait time for sending keys, leading to

After upgrading to protractor 2.0, I encountered some issues in my project. An expect() statement fails because the given text is '', it appears that the expect is being executed before sendKeys() is completed. elem.clear().sendKeys('Messa ...

Eliminating redundant subdocuments in MongoDB

This particular schema represents a single document out of thousands in the database, all housed within the same collection. Document 1: { pageNumber: 0, results: [ { jobkey: "AAA", }, { jobke ...

What is causing Angular services to malfunction when used within setTimeout and setInterval functions?

manage-tasks.component.html <p>manage-tasks works!</p> <form #taskForm="ngForm"> <input type="text" name="task_name" palceholder="Task Name" [(ngModel)]="task_service.selected_task.name& ...

What is the best way to transfer data to a modal in React.js?

In my table, I am using .data.map() to return data like this: {this.state.data.map((item, i) => { return ( <tr> <td>{item.id}</td> <td>{item.name}</td> ...

What steps can I take to pinpoint the exact error location when running assetic:dump in Symfony2?

This error message indicates an issue with assetic:dump in Symfony2. [Assetic\Exception\FilterException] ...

"Is it possible to create a for loop that iterates over each individual mesh in a

I'm searching for a way to achieve the following: scene.forEachMeshInScene(function(mesh){ //Perform actions here }); Unfortunately, this capability does not currently exist. Any suggestions on how to accomplish a similar functionality? ...

Is it possible to create a TypeScript generic type that transforms a Record into a type by utilizing the `as const` keyword?

Imagine this scenario: I define const foo = { myKey: 'myValue' } as const Now, when I ask for typeof foo, I get { readonly myKey: 'myValue' } If I have a type MyType = Record<string, string>, and I want to create a modifier (let ...

unable to choose the element

Initially, I successfully selected an element using ng-repeat. However, the developers have now implemented virtual repeat, rendering the following code ineffective. expect(stores.listStores(0).getText()).toContain('Prahran'); expect(element.all ...

What could be the reason for my DataTables plugin not functioning properly?

I've been struggling to implement the DataTables plugin on my website. Despite ensuring that all necessary css and js files are correctly linked in my html code, the tables still don't display as expected. I have included both my html and relevan ...

How wide can we make the Outerbounds in the Chrome app?

My setup includes a chrome box that can accommodate two monitors. I am interested in creating a single chrome app with dimensions of 3840x1080 (width =3840, height =1080) to cover both screens. I attempted this but was unsuccessful. Are there any alterna ...

I am experiencing an issue with my images not loading properly upon initial loading in Safari, while all other browsers are working perfectly. What

Currently, I am utilizing the 3D card-flip method on my website and it is functioning flawlessly in Firefox, IE, and even the downgraded versions of IE for older browsers. However, I have encountered an issue with Apple iOS devices and Safari. It appears ...

What causes the disparity between Chrome's print preview and printed output? [HTML - CSS]

In my Angular demo project, I have included basic text and a table. There is a print button that calls window.print() to print the page with applied styling. printPage() { window.print(); } CSS: @media print { @page { size: landscap ...

How to ensure a C# web request waits for a webpage to finish loading, including all jQuery and AJAX calls

Hey all! Just had a quick question that I hope someone can help me with. Right now, I'm utilizing an HttpClient to send a request to a website and then parse the data from the page. However, the issue that I'm running into is that a lot of the co ...

Attach the document for submission from a different source

Utilizing a jQuery DataTable with the capability of containing multiple rows, each row is populated using a modal. Depending on the selected values, each row may or may not have an attachment. This table is located inside a form. The issue arises when atte ...

This TypeScript error occurs when trying to assign a value of type 'null' to a parameter that expects a type of 'Error | PromiseLike<Error | undefined> | undefined'

Currently, I am making use of the Mobx Persist Store plugin which allows me to store MobX Store data locally. Although the documentation does not provide a TypeScript version, I made modifications to 2 lines of code (one in the readStore function and anot ...

I love the idea of the music playing on as I navigate between pages or tabs. Such a cool feature with Next

I'm looking to implement a music player within my next.js application. How can I ensure that the currently playing track doesn't stop when switching between pages? Essentially, I want the music playback to continue seamlessly as users navigate th ...