Refresh the view in AngularJS following a successful $http.get request

I have a <ul> in my HTML view that is populated based on a $http.get request.

HTML:

    <div id="recentlyReleased" ng-controller="sampleRecordController as recCtrl">
    <h1>Sample Records</h1>
    <ul>
        <li class="last-child" ng-repeat="record in recCtrl.records">
            <a target="_new" ng-href="" >
                <span>sample 1</span>

            </a>
        </li>
    </ul>
     <a ng-click="recCtrl.displayRecords('a')" href="">
         <img />
     </a>
     <a ng-click="recCtrl.displayRecords('b')" href="">
         <img />
     </a>
</div>

Factory

angular.module('homeApp.services', [])
    .factory('homePage', function ($http) {
        return {
            showRecords: function (fac) {
                return $http.get('/home/getRandom?num=10&fac=' + fac)
                        .then(function (response) {
                            return response.data
                        });
            }               
        }

    }

    );

Controller

angular.module('homeApp.controllers')
    .controller('sampleRecordController', function (homePage) {
        var r = this;
        r.base_url = base_url;
        r.records = [];
        var currentFac='c';
        r.displayRecords = function (fac) {
            homePage.setFac(fac);
            homePage.showRecords(homePage.getFac()).then(function (data) {
                r.records = data;
            });

        },
        r.displayRecords(currentFac); //initial load

    })

Although the initial loading of the <ul> list works fine, clicking on the <a> link does not refresh the HTML view. As a beginner in AngularJS, I would appreciate any guidance on how to resolve this issue. Thank you!

Answer №1

If you want to properly handle asynchronous operations in AngularJS, make sure to return the promise of $http.get() as shown below:

angular.module('app.services', [])
.factory('dataService', function ($http) {
    return {
        fetchData: function (param) {
            // return the promise here
            return $http.get('/api/data?param=' + param);
        }               
    }
});

angular.module('app.controllers')
.controller('sampleController', function (dataService) {
    var vm = this;
    vm.data = [];
    var parameter='example';
    vm.loadData = function () {
        dataService.fetchData(parameter)
        .then(function (response) {
            vm.data = response;
        });
    };
    vm.loadData(); //initial load
});

Remember, do not try to return the response of an AJAX call directly because it operates on a separate thread and you won't be able to determine when the call will finish. It's essential to understand how promises work in AngularJS.

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

Using jQuery to locate a JavaScript variable is a common practice in web development

I recently created a JSFiddle with buttons. As part of my journey to learn jQuery, I have been converting old JavaScript fiddles into jQuery implementations. However, I seem to be facing a challenge when it comes to converting the way JavaScript fetches an ...

Is the availability of XMLHttpRequest constant?

When using XMLHttpRequest to retrieve data from the server with Javascript, is it necessary to include conditional checks for the specific browser being used? Is the code snippet below considered standard practice when working with XMLHttpRequest? if (w ...

A helpful guide on rendering nested maps from JSON data in React.JS

I am attempting to display menu values from a JSON data. This menu has multiple levels, so I am using a nested map function to render the complete menu. const menu = { data:[ { title: "Home", child: [ { title: "SubL ...

When attempting to check and uncheck checkboxes with a specific class, the process fails after the first uncheck

I have a set of checkboxes and one is designated as "all." When this box is clicked, I want to automatically select all the other checkboxes in the same group. If the "all" box is clicked again, I would like to deselect all the other checkboxes. Currently ...

Count of elements in one flexbox row

Having a flexbox container with multiple items in row-wrap format, is there a way to use JavaScript to determine the number of items in each row? Essentially, finding out at what point they wrap. For instance- <div class="container"> <div clas ...

In order to verify the dynamic components within the table

I need assistance with validating dynamically created textareas. In the code below, I am able to validate only the first row but struggling to do so for the second row. How can I get all the row values validated? Thank you in advance. To generate dynamic ...

The property was computed but cannot be set - specifically for a toggle component

I am currently working on developing a switch toggle component in Vue that includes a v-model and @updated. However, I am encountering difficulties when trying to update the model once the user toggles the switch. Initially, I faced an issue regarding muta ...

Struggling with setting up a search bar for infinite scrolling content

After dedicating a significant amount of time to solving the puzzle of integrating infinite scroll with a search bar in Angular, I encountered an issue. I am currently using Angular 9 and ngx-infinite-scroll for achieving infinity scrolling functionality. ...

Unable to retrieve the data from MongoDB

Struggling to retrieve data from MongoDB, my code in the server.js file is not working as expected. You can view the code here. This is the route I'm using in Insomnia for GET requests: here However, when I test it in Insomnia, I receive the followi ...

"Learn how to use pure JavaScript to show the output of a PHP file on a webpage

I created a basic PHP file named hello.php that shows a 'hello world' message as follows: <?php echo "Hello world!"; ?> Now, I am looking to store this message in a JavaScript variable. How can I achieve this? <script type="tex ...

Would it be expected for these two JQuery functions to exhibit identical behaviors?

If I have the following two JQuery functions - The first one is functional: $("#myLink_931").click(function () { $(".931").toggle(); }); The second one, however, does not work as expected: $("#myLink_931").click(function () { var class_name = $(thi ...

I'm having trouble with my Express server routes not being accessed. The browser is displaying an error message saying 'No Data Received ERR_EMPTY_RESPONSE

I've encountered an issue with my express server while setting up an email service. Despite troubleshooting and simplifying the code to a basic 'hello world' example, the problem persists. No routes are functioning properly – requests made ...

Enhancing date formatting with Angular and Pikaday

I am currently utilizing the angular-pikaday plugin (available at https://github.com/nverba/angular-pikaday) and encountering an issue with date formatting. My objective is to have a model containing a date string formatted as YYYY-MM-dd. To address this ...

Initiating and pausing an Interval using a single button

I'm attempting to create a JavaScript-based chronometer that starts and stops when a single button is clicked. However, I am struggling to figure out how to properly implement the setInterval function to achieve this functionality. Below is my current ...

The Document.querySelector() method is not displaying every element

As a beginner, I am currently exploring the world of relative CSS selectors and JSPath for my automation scripts. During my journey, I noticed that there are differences in the return statements between these two methods. Below is an example demonstrating ...

What causes Angular2 to detect both reference changes and primitive changes even when the OnPush flag is enabled?

Take a look at this code snippet import {Component, OnInit, Input, OnChanges, DoCheck, ChangeDetectionStrategy} from 'angular2/core' @Component({ selector: 'child1', template: ` <div>reference change for entire object: { ...

Working with Javascript objects and arrays

Need assistance with manipulating/updating a JavaScript array. Hoping for some help. The initial array looks like this: array('saved_designs'=array()); In Javascript JSON format: {"saved_design":{}} I plan on adding a label and its associa ...

Updating the value of a global variable through dependency injection in AngularJS

One thing I consistently do is inject app.constant('DOCUMENT_ID', window.documentId || 1); into services, controllers, and directives. I'm now looking to convert DOCUMENT_ID into a global variable. The goal is for any changes made to DOCUME ...

Issue: The DLL initialization routine failed for electron, but it works perfectly fine on node.js

Currently, I am facing an issue while attempting to load a custom module in electron that is written in D using the node_dlang package. The module loads successfully with node, but encounters failures within electron. The test run with node, which works w ...

Module not found (Error: Module not found for './models/campground')

Here is the code snippet I am working with: var express = require("express"), app = express(), bodyParser = require("body-parser"), mongoose = require("mongoose"), Campground = require("./models/campground"), Comment = require("./mode ...