Troubleshooting issue with DOM not refreshing after making a $http POST request in a MEAN

I am working on an app that interacts with a Mongo database through CRUD operations. Currently, I have a form input where users can add elements, and I want these elements to appear below the form in real-time as they are added. However, at the moment, the new elements only show up after refreshing the page. Interestingly, when I click on an "x" button which triggers an ng-click event to delete an item (and consequently remove it from the database), the element disappears immediately without requiring a page refresh. Both my POST and DELETE requests are handled using promises, but for some reason, only the delete requests automatically update the DOM, while the post requests do not.

Below is the code snippet of my controller:

app.controller('ListController', function($scope, PlaceService) {

    $scope.places = [];

    getPlaces();
    function getPlaces() {
        PlaceService.findAll().then(function(promise) {
            //Although $scope.places updates correctly, the changes are not reflected in the DOM
            $scope.places = promise.data;
        });
    };

    $scope.submit = function(place) {
        if (!place) return alert('No content submitted');
        PlaceService.submit(place).then(function(data) {
            getPlaces();
        }, function(error) {
            console.log(error)
        });
    };

    $scope.remove = function(id) {
        PlaceService.remove(id).then(function(data) {
            getPlaces();
        }, function(error) {
            console.log(error)
        });
    }

});

The PlaceService factory handles communication with the API and looks like this:

app.factory('PlaceService', function($http, $q) {

    return {

        findAll: function() {
            var deferred = $q.defer();
            $http.get('/places').then(function(response) {
                console.log('Get Request Successful');
                return deferred.resolve(response);
            }, function(err) {
                return console.log(err);
            });
            return deferred.promise;
        },
        remove: function(id) {
            var deferred = $q.defer();
            $http.delete('/places/' + id).then(function(response) {
                console.log('Delete Successful');
                return deferred.resolve(response);
            }, function(err) {
                return console.log(err);
            });
            return deferred.promise;
        },
        submit: function(entry) {
            var deferred = $q.defer();
            var jObj = JSON.stringify(entry);
            $http.post('/places', jObj).then(function(response) {
                console.log('Post Successful');
                return deferred.resolve(response);
            }, function(err) {
                return console.log(err);
            });
            return deferred.promise;
        }

    }
});

I have attempted using $timeout to make $scope.places reflect the updates in the DOM, but so far, it has not worked as expected.

TLDR: Updates made to $scope.places in the controller are not being reflected in the DOM

Answer №1

Make sure to incorporate the use of .then() in both your $scope.submit and $scope.remove functions so that the execution of your getPlaces() function will occur only after the POST or DELETE actions have been successfully completed.

Answer №2

SubmitHandler.sendData(place) is a $q promise. This indicates that, if you wish to execute fetchData(); after successfully submitting a "place", you must include it in your callback:

SubmitHandler.sendData(place)
   .then(function(response) {
      fetchData();
   }, function(error) {
    // handle any errors
   });

You should also apply the same approach for the SubmitHandler.delete(place) method.

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

Guide on integrating react-tether with react-dom createPortal for custom styling of tethered components based on their target components

Within a Component, I am rendering buttons each with its own tooltip. The challenge is to make the tooltip appear upon hovering over the button since the tooltip may contain more than just text and cannot be solely created with CSS. The solution involves ...

Challenges with ExpressJS 4 middleware

Trying to grasp the concept of middleware in ExpressJS 4 has been quite a challenge for me. As far as I understand, middleware are applied based on the order they are declared and can be "bound" at different levels. My current focus is on binding a middl ...

`Multiple Autocomplete feature that allows rendering of previously selected items`

I've encountered a slight issue with my autocomplete feature. On the same page, I have two different autocompletes set up. Both of them pull elements via ajax from separate sources and use the _render option to display the items. The problem arises wi ...

What steps are needed to set up my Express server so that it can render all my content, rather than just my HTML file?

I need help setting up a server for my project using Express. Here is the structure of my file directory: root-directory ├── public │ ├── css │ │ └── styles.css │ ├── images │ │ └── img1.png | | └ ...

The Angular 1.5 directive utilizes one-way binding to seamlessly update the parent scope

I am experiencing an issue with a directive that has an isolated-scope and one-way binding variable. Despite setting up the directive to keep the scope separate, any changes made to the variable in the directive controller also update the parent scope. Be ...

Error: Unable to access the 'login' property of an undefined object

An error occurred: Uncaught TypeError: Cannot read property 'login' of undefined........... import Login from '../components/Login.jsx'; import { useDeps, composeWithTracker, composeAll } from 'mantra-core'; export const com ...

What is the best way to combine two objects in AngularJS?

https://i.sstatic.net/qr5Bb.png If you have two JSON objects that need to be merged while removing duplicate properties, what approach would you take? ...

Utilizing the combination of Mongodb and Mysql within a single project

For the past week, I've been dedicated to mastering Mongodb for my project. The main goal of my project is to store extensive geolocation data, and I believe that Mongodb is the most suitable database for this purpose. Speed is crucial for me, and Mon ...

Determination of an arc trajectory using JavaScript

I have been trying to figure out how to replicate this effect. The Red arrowhead remains stationary while the background features a curved path. Currently, I am adjusting the background position to give the illusion of the arrowhead moving along the curved ...

Which database system is best suited for a survey application tool: SQL or No

I'm currently in the process of developing a survey tool that will empower users to create their own surveys and polls. In order for this tool to be effective, it must include features such as the ability to design questions, upload files, login, regi ...

AJAX not showing validation error message

For the past two days, I've been grappling with an issue and can't seem to pinpoint where it's coming from. After leaving the textbox, the Ajax call functions correctly and returns results as either true or false, triggering the success fun ...

Attempting to halt the execution of code within an Express.js route

At the moment, I am working on a basic Express route with Node.js. In a scenario where a specific condition is met in a MongoDB query, my intention is to redirect the user and halt any further execution of the code. I have experimented with various approa ...

JavaScript and CSS animations offer dynamic and engaging ways to bring

I'm working on a div section and I want it to come down and rotate when a button is clicked. However, after moving to the bottom, it doesn't rotate as expected but instead returns to its initial position along the Y axis. How can I fix this issue ...

What do you call a JavaScript function when it has a name

This code is confusing to me. It's not the usual JavaScript syntax for a function that I know of. Is this a specific function? Or perhaps it's a callback for when an update event occurs? Apologies for these beginner questions, as I am quite new t ...

Prevent the ability to reload and use the F5 key on my PHP page

Currently, I am utilizing a timer on my PHP page. However, whenever someone refreshes the page, the timer resets from the beginning. I am looking for a solution to disable the ability to refresh the page using F5 or reload options within my PHP page. Appr ...

React JS's popup feature can be unreliable, as it tends to break the application frequently

I have been developing a web application that interacts with a public API and presents the retrieved data in a table format. However, I am encountering an issue where clicking the "Click to Display Hottest Planet" button sometimes results in an error. How ...

Angular facing problems with tracking comment counts in Disqus

After successfully setting up the Disqus comments system on my Angular website following the guide at , everything was working fine. However, when attempting to add the Disqus comment count system to my homepage using the code provided at , I encountered a ...

Steps to improve the appearance of the Header on a dataTable during Dragging

I am working on creating a table that can be reordered using mat-table and MatTableDataSource. However, I would like the column to have a white background color instead of being transparent when dragged. Is there a way to achieve this? <table mat-tab ...

Incorporate attributes into object properties in a dynamic manner

Currently, I am experimenting with bootstrap-multiselect and my goal is to incorporate data attributes into the dataprovider method. Existing Data Structure: var options = [ {label: 'Option 1', title: 'Option 1', value: ' ...

"Encountering a 404 error while trying to refresh

I've already attempted to include <base href="/index.html"> and/or <base href="/"> My .htaccess configuration is as follows: Options +FollowSymLinks <ifModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME ...