The issue with AngularJS multiple $http requests failing to fetch accurate data

I'm having issues with my AngularJS controller and service modules. I want to refresh custController.allCustomers after adding a new customer so that the UI displays the new data. However, when I call custController.createCustomer, the new customer doesn't show up in allCustomers. I suspect there's a problem with how I'm using promises. Can someone help me troubleshoot this?

controllers.js

// AngularJS Customer Controller
angular.module('CustomerModule')
.controller('CustomerController', function ($log, CustomerService) {
    console.log("CustomerController initializing");
    var custController = this;
    custController.newCustomer = {};

    custController.refresh = function () {
        CustomerService.getAllCustomers().then(function (response) {
            custController.allCustomers = response.data;
        });
        custController.newCustomer = {};
    };

    custController.createCustomer = function (customer) {
        CustomerService.createCustomer(customer).then(function (response) {
            custController.refresh();
        });
    };

    custController.refresh();
});

services.js

// AngularJS Customer Service
angular.module('CustomerModule')
.service('CustomerService', function ($http) {
    var service = this;

    service.getAllCustomers = function () {
        return $http.get("http://localhost:8080/customers");
    };

    service.createCustomer = function (customer) {
        console.log("Creating customer ", customer);
        return $http.post("http://localhost:8080/customers", customer);
    };
});

Additional app code:

// AngularJS App Configuration
var app = angular.module('CustomerModule', ['ngRoute']);

app.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: '../dashboard.html',
            controller: 'CustomerController',
            controllerAs: 'custController'
        })
        .when('/dashboard', {
            templateUrl: '../dashboard.html',
            controller: 'CustomerController',
            controllerAs: 'custController'
        })
        .otherwise({redirectTo: '/'});
}]);

index.html

<!DOCTYPE html>
<html lang="en" ng-app='CustomerModule'>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-route.min.js"></script>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<!-- Body content goes here -->

dashboard.html

<!-- Dashboard HTML content goes here -->

Answer №1

You have implemented the use of "one-time" binding expressions within your HTML code. According to the documentation:

An expression that starts with :: is considered a one-time expression. One-time expressions will cease recalculating once they reach stability, which occurs after the first digest cycle if the expression's result is not undefined (refer to the value stabilization algorithm).

It is important to note that this differs from "one-way" binding where values update in only one direction. Here, the view will no longer be updated once the value has stabilized (i.e., it is defined and does not change).

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

All-in-one Angular script and data housed within a single document

Context I want to design a personalized "dashboard" to assist me in staying organized. This dashboard will help me keep track of the issues I am currently handling, tasks I have delegated, emails awaiting response, and more. While I am aware of project ma ...

Use jQuery to compare the input values whenever they are modified

I am trying to synchronize the input values of two inputs as they are typed in. The code I have seems to work sometimes, but not consistently. Here is the code snippet: $('#google-querynav').keypress(function() { var text = $(this).val(); ...

What is the process for obtaining a push key in Firebase?

When a user submits data to the Firebase database, I need to handle the Key generated by that action in my own function. The challenge arises when a user fills out a form and sends data to our real-time DB. This data may include optional images, and I wan ...

Provide solely the specified content range

While working with Node.js, my goal is to develop a video server that can serve a specific portion of a larger media file. Thanks to this gist, I have successfully created a video server and integrated it with an HTML5 video player using: <video contr ...

Buttons in Datatables fail to appear when using ajax loading

I've been trying to solve this issue for a while now, but I just can't seem to figure it out. According to the documentation, adding initComplete should make the buttons appear, but I am still facing difficulties. Am I overlooking something? I&a ...

What is the best way to animate changes to a background image using jQuery?

Exploring the possibilities of creating a unique visual effect reminiscent of a pulsing heartbeat for a button. I'm under the impression that achieving this is beyond the scope of CSS. Can anyone shed light on how to implement an animated background ...

Adjust rankings based on the number of upvotes received by a project

I'm facing a challenge with ranking projects based on the number of votes they receive. No matter the vote count, the project always ends up getting ranked as 1. To address this issue, I developed a function to manage the rank count and a return hand ...

I'm curious about utilizing jsviews in conjunction with jquery sortable

Check out my jsFiddle Example where I am using jsViews in conjunction with JQuery sortable. By default, the remove function works fine; however, when you change the order of items and then try to delete one, multiple items are removed. How can this issue ...

Browsing through an array of objects in PHP

Currently working on creating an array of objects using jQuery. var selected_tests = $("#selected_tests").find("tr"); jsonLab = []; $.each(selected_tests, function() { jsonLab.push({ test: ($(this).children()).eq(0).text(), amount: ($(this).chil ...

The value of element.scrollTop is consistently zero

Why does the scrollTop position of an element always return 0? How can I correct this issue? JSFiddle var inner = document.getElementById('inner'); window.addEventListener('scroll', function() { console.log(inner.scrollTop); }) # ...

Retrieve the exact value of a key within a string

This is my unique text: let x = "Learning new things every day!"; I am utilizing the substring() method to extract a specific part of it: console.log(x.substring(9, 12)); Instead of the entire string, I only want the word 'new'. let x = "l ...

There was a parsing error due to an unexpected token, and we were expecting a comma instead

Below is the code snippet written in react js: class Posts extends Component { render() { return ( {console.log('test')} ); } } When I executed this code, an error occurred stating: Parsing error: Unexpected token, expected " ...

Error: Unable to access 'target' property as it is undefined in React JS

I am currently working on capturing the value of a select tag that triggered an event, but I am encountering an issue when changing the tag. An error message pops up saying TypeError: Cannot read property 'target' of undefined. It seems to indica ...

How can I modify the parent form element to only evaluate the expression at the text node, without affecting Angular interpolation?

Currently, I am in the process of developing an eCommerce platform and utilizing angular to construct a widget on product detail pages. Unfortunately, my control over the initial HTML rendered for the browser is quite limited. While most tasks related to m ...

Firebase Error: The creator key was not defined, which cannot be passed as undefined in JSON. Instead, use null

Currently, I'm working on a project using angularFire 0.8.2. The project is actually based on thinkster.io's angular-firebase tutorial. However, I've encountered a hurdle when trying to create a custom user profile and access the data within ...

It appears that the collection.add() method in connector/node.js only successfully executes one time

Currently, I am experimenting with MySQL Document Store to compare it with our relational tables. To achieve this comparison, I am working on transforming our existing table into a collection. The table contains approximately 320K records that I need to ...

Why does my POST request result in an express get being triggered?

When my express server runs the deliverCard() method, it sends a set of key/value pairs. app.get('/', (req, res) => { let card = deck.deliverCard(); console.log('get', card) res.render('layout.ejs', {element:card}); ...

Double the Trouble: jQuery AJAX Making Two Calls

I've already posted a question about this, but I have now identified the exact issue. Now, I am seeking a solution for it :) Below is my code snippet: $('input[type="text"][name="appLink"]').unbind('keyup').unbind('ajax&apos ...

Having trouble running tests on the Express.js server

I'm struggling to run basic tests on my expressjs server and close it immediately. I have exported the server as a promise, but can't seem to figure out how to achieve this. Below is the code for my server file : index.js const config = require( ...

Issue with Vuetify v-alert not appearing after updating reactive property

I am trying to set up a conditional rendering for a v-alert if the login response code is 401 Unauthorized. Here is how I have defined the alert: <v-alert v-if="this.show" type="error">Invalid email and/or password.</v-alert> Within the data ...