Angular post request does not update the table

After displaying a table and a form on a page, I encountered an issue where the table does not update with new data when submitting the form. Even after refreshing the page, the new data is not reflected. As a newbie to Angular, I'm unsure of what exactly is causing this problem.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
  integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
  <!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

<script
              src="https://code.jquery.com/jquery-2.2.4.min.js"
              integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
              crossorigin="anonymous"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>

  <body>
    <div ng-app="myApp">
      <div class="container">
        <div ng-controller="getCtrl">
            <table class="table table-stripped">
              <tr>
                <th>Nombre</th>
                <th>Apellido</th>
              </tr>
              <tr ng-repeat = "user in users">
                 <td>{{user.name}}</td>
                 <td>{{user.lastName}}</td>
              </tr>
            </table>

            <div class="row" >

              <form name="userForm" ng-submit="formSubmit()">
                <div class="form-group">
                  <label>Nombre</label>
                  <input type="text" name="name" class="form-control" ng-model="user.name">
                  <span ng-show="errorName">{{errorName}}</span>
                </div>

                <div class="form-group">
                  <label>Apellido</label>
                  <input type="text" name="lastName" class="form-control" ng-model="user.lastName">
                  <span ng-show="errorName">{{errorName}}</span>
                </div>
                <div style="text-align:center">
                  <button type="submit" class="btn btn-primary" >Insertar</button>
                </div>
              </form>
            </div>
        </div>
      </div>

    </div>

    <script src="node_modules/angular/angular.js"></script>
    <script src="app.js"></script>
  </body>
</html>

The JavaScript file looks as follows:

var app = angular.module('myApp',[]);

app.controller('getCtrl',['$scope','$http',function($scope,$http){
  $http.get("http://127.0.0.1:3000/api/Users")
  .then(function(response){
    $scope.users = response.data;
  });

  $scope.errorName = false;

  $scope.formSubmit = function(){
    $http.post("http://127.0.0.1:3000/api/Users",$scope.user)
    .then(function(response){

    });
  };
}]);

Potential Solution:

As someone who is new to Angular, here is my proposed solution for the issue at hand. Would appreciate feedback on whether this implementation adheres to best practices:

var app = angular.module('myApp',[]);

app.controller('getCtrl',['$scope','$http',function($scope,$http){

  $scope.makeGetRequest = function(){
    $scope.users = {};

    $http.get("http://127.0.0.1:3000/api/Users")
    .then(function(response){
      $scope.users = response.data;
    });
  }
  $scope.errorName = false;
  $scope.makeGetRequest();

  $scope.formSubmit = function(){
    $http.post("http://127.0.0.1:3000/api/Users",$scope.user)
    .then(function(response){
      $scope.makeGetRequest();
    });
  };
}]);

Answer №1

If you want to see it locally or refresh the list after a successful callback, follow these steps:

Give this a shot.

$scope.formSubmit = function(){
    $http.post("http://127.0.0.1:3000/api/Users",$scope.user)
    .then(function(response){
       //to update the local array with the posted object
       $scope.users.push($scope.user);
    });
  };

Trust this solution comes in handy.

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

What steps do I need to take to successfully implement a $.fn. function that runs automatically when it is called?

I'm struggling with the following piece of code: function init() { var $contentButtonPanel: JQuery = $('#content-button-panel') $contentButtonPanel .find('.arbo .toggle, .collapsible-list li:has(ul) > ...

Dominant Editing through ASP.Net Roles

Looking for guidance on how to effectively use knockout with asp.net membership roles in MVC 4. My goal is to incorporate an editable grid on the page based on whether the user is an administrator or a 'registered user'. I want to ensure that use ...

Maintaining Flexbox layout without triggering item re-rendering for a new container

This is the unique layout I'm aiming to create: I am facing a challenging flexbox layout that needs to be implemented. One of the items in this layout is a Webgl player, which cannot be conditionally rendered due to the restarting issue it may cause. ...

Encountered an issue while attempting to load the required module

I'm having trouble setting up Stripe for my app and getting errors when trying to implement the module. Typically, I would require the module at the top of the file in order to use it, but when I do this in the paymentCtrl file, it doesn't work a ...

Glitch found in Safari involving innerText of elements

Hey everyone, I posted this question not too long ago but now I have some images to share regarding the issue with Safari. When checking the console in Safari, the following text is displayed: <div id="rot3posDisp" class="rotDisp">C</div> Ho ...

What is the best method for enabling HTML tags when using the TinyMCE paste plugin?

After spending countless hours searching for a solution, I am still puzzled by this problem. My ultimate goal is to have two modes in my powerful TinyMCE editor: Allowing the pasting of HTML or Word/OpenOffice text with all styles and formatting attribu ...

CSRF validation did not pass. The request has been cancelled. The failure occurred due to either a missing or incorrect CSRF token

Upon hitting the submit button in the login form, I encountered the following error message: Forbidden (403) CSRF verification failed. Request aborted. CSRF token missing or incorrect. settings.py MIDDLEWARE = [ 'django.middleware.security.Secur ...

Tips for troubleshooting an Angular error when no specific information is provided

I'm encountering an error `ERROR Error: "[object Object]" in my console and my app is displaying a white screen. Everything was working perfectly fine before, and I can't pinpoint any changes that may have caused this issue. The error appears to ...

Having issues with the latest version of Fabric JS code running properly

Hello, I stumbled upon this JS fiddle (http://jsfiddle.net/efmbrm4v/2/) and I really need something similar to function properly. The fiddle uses an older version of fabric js (1.4.0) and I'm having trouble getting it to work with the newer versions ( ...

Refining an array data table within a nested component

Transitioning my old PHP/jquery single-page applications to VueJS/Webpack has been a journey I'm undertaking to familiarize myself with the latter technology. It involves converting a simple table that pulls data from a JSON API and incorporates filte ...

The error message "TypeError: 'undefined' is not a function (evaluating '_.contains')" appeared during the karma test

While executing my karma tests, I encounter a specific error during the jenkins build process. Interestingly, everything works perfectly fine when running the tests locally and all pass without any issues. However, once the same code is executed on the jen ...

switching from grunt's autoprefixer to grunt's postcss

Since grunt-autoprefixer has been deprecated, I am looking to transition to grunt-postcss. Being new to the world of grunt and its dependencies, I couldn't find clear instructions in the documentation for this migration process. To complete the migr ...

How to trigger a hover effect on a div and its child simultaneously using HTML and jQuery

Here's my concept: I want the text to be contained within div elements with an integrated image, rather than just having fading in and out pictures. Here's my attempt: #first{ position: absolute; } #second{ position: absolute; -we ...

What is the best way to initiate the registration page through the @auth0/auth0-react library?

I've hit a roadblock in trying to automatically launch the sign-up (registration) page using @auth0/auth0-react. Previously, I would send mode which worked with auth0-js. So far, I have attempted the following without success: const { loginWithRedir ...

What is the process for triggering data-dismiss after the href has been activated?

Could someone help me with this issue? <a class='btn btn-danger' href='page.html'>Delete</a> I am trying to activate the "data-dismiss" attribute after the "href" is activated. My initial attempt was using this code: < ...

URL base not refreshing on globalized Angular web application

I have recently expanded my Angular web app to include new languages, but I am encountering a strange issue. Despite setting up all the new languages in my angular.json file and linking their respective language files correctly, I am facing a problem with ...

Optimal way to send simulated data to Angular and Ionic applications

Currently, I am developing a mobile app using Ionic and AngularJS as the primary framework. However, I have encountered a problem that I need to address. I prefer not to send an HTTP request from my app to the backend API (which is built on Ruby on Rails) ...

Issue communicating with connect-flash: flash variable is not recognized

I've been diving into books on node.js, express, and mongodb lately. In one of the examples, the author showcases the usage of connect-flash. However, I'm encountering some difficulties getting it to function as expected. Below are snippets from ...

Invoking JavaScript function from an Android Activity

I have a simple JS function that is supposed to set values of some html contents, but it doesn't seem to be working properly. Here is the code for the JS function: function SetEdits(name,email,pic,date) { document.getElementById("myPic").src=pic; doc ...

Issue: Incorrect comparison of two dates leading to inaccurate results

I have been attempting to compare two dates within a UI-GRID, and although I have the dates in the correct format, it seems to always provide a false result. Below is the code: filters: [{ condition: function (term, value) { if (!term) return ...