AngularJS experiencing issues with bidirectional data binding functionality

I have a simple CRUD app that I am working on. It consists of a form with just a single text box, and all the entries submitted through the box should be displayed in a grid below the text box.

Everything seems to be working fine, except for the fact that the grid does not update with new entries unless the page is refreshed. My setup includes a loopback API running on localhost:3000 while my angular app is on localhost:9000. The database being used is MySQL.

The same code works perfectly if I use the MEAN stack. However, now we need to support MySQL and decouple the API from my application. Here is the controller:


    angular.module('dashboardApp')
      .controller('StateCtrl', function ($scope, $http) {
         $scope.formData = {};
         $scope.baseUrl = '//localhost:3000/api/v1/states';

         $http.get($scope.baseUrl).success(function(states) {
           $scope.states = states;
         });

        $scope.create = function() {
          $http.post($scope.baseUrl, $scope.formData)
            .success(function(states) {
              $scope.states = states;
            })
            .error(function(states) {
              console.log('Error: ' + states);
           });
        };
     });

This is the view:


    <form class="form-inline" role="form" data-ng-submit="create()">
      <div class="form-group">
        <label class="sr-only" for="name">State</label>
        <input type="text" class="form-control" id="name" placeholder="Enter state"  ng-model="formData.name">
     </div>
     <button type="submit" class="btn btn-default">Enter</button>
    </form>

    <table class="table table-striped">
  <tr ng-repeat="state in states">
        <td>{{state.name}}</td>
  </tr>
    </table>

Any assistance would be greatly appreciated. Just a quick note: I've also attempted to use services/resources instead of $http.

Answer №1

It seems that the issue at hand is the difference in return values between $http.get and $http.post within the $scope.create function.

  1. You need to add the returned object to the $scope.states array. Alternatively, you can...
  2. Modify the $http.post request to return an array which can then be assigned to $scope.states

    angular.module('dashboardApp') .controller('StateCtrl', function ($scope, $http) { $scope.formData = {}; $scope.baseUrl = '//localhost:3000/api/v1/states';

     $http.get($scope.baseUrl).success(function(states) {
       $scope.states = states; // this returns an array
     });
    
    $scope.create = function() {
      $http.post($scope.baseUrl, $scope.formData)
        .success(function(states) {
          //$scope.states = states; // this return an object
          // Instead, do this
          $scope.states.push(states);
        })
        .error(function(states) {
          console.log('Error: ' + states);
       });
    };
    

    });

Note: It's also possible to have $http.post return the entire array.

Answer №2

When implementing Cross-Origin Resource Sharing (CORS), it is essential to include the necessary HTTP Access-Control-Allow-Origin header in your API service. Failure to do so may result in the browser blocking the response. To troubleshoot issues, consider adding an error callback to your $http.get() method.

Answer №3

Agreeing with @Maurice, it seems like you may be encountering a cross domain problem due to the involvement of two ports, 9000 and 3000. If the expected data is in json format, you can attempt to include this in your url:

$scope.jsonpUrl = $scope.baseUrl+"?callback=JSON_CALLBACK";

$http.jsonp($scope.jsonpUrl)
.success(function(states) {
    $scope.states = states;
})
.error(function(data, status, headers, config) {
    // executed asynchronously in case of an error
    // or when the server responds with an error status.
    console.log("Error:", data);
});

Give this approach a shot and inform us about the results. Cheers!

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

Capturing the value of an input field within a controller in AngularJS

I have been programming with JSP and Angular JS. Currently, I am faced with a scenario where I need to work with a JSP page containing a hidden input field. To set the value of this input field, I am using a session attribute like so: String policy = (S ...

The input '{ data: InvitedUser[]; "": any; }' does not match the expected type 'Element'

I'm currently facing a typescript dilemma that requires some assistance. In my project, I have a parent component that passes an array of results to a child component for mapping and displaying the information. Parent Component: import { Table } fr ...

The middleware in ExpressJs does not seem to function properly following its import

Below is the code snippet from my app.js file: import path from 'path'; import bodyParser from 'body-parser'; import express from 'express'; import defender from 'inflex-defend-api'; import { key, secret } from &a ...

Having trouble updating an array in a mongoose document?

Need help with updating an array in a document by adding or replacing objects based on certain conditions? It seems like only the $set parameter is working for you. Here's a look at my mongoose schema: var cartSchema = mongoose.Schema({ mail: Stri ...

Issue with ngFor in Angular 2 causing error message in console

I'm currently following a guide to create a basic page that showcases different courses. However, I've encountered an error while testing the code in the console. The Angular 2 dependency is listed as "angular2": "2.0.0-beta.7". I have also attem ...

Oops! The controller in AngularJS is throwing an error due to an undefined variable in the

As I work on building my portfolio with AngularJS, I have created a projects.json file to store all of my projects. My goal is to have a modal open when I click on a specific project button. To achieve this, I wrote a function that takes an id as an argu ...

The cloned rows created with jQuery are failing to submit via the post method

Hello, I am currently working on a project in Django and could use some assistance with my JavaScript code. Specifically, I am trying to incorporate a button that adds new rows of inputs. The button does function properly as it clones the previous row usin ...

Storing information within a global variable array or exploring alternative methods

I am currently working on a project in electron / node.js and need assistance with the following tasks: Importing data from excel/csv files Visualizing the data using d3.js Cleaning the data by removing duplicates, etc. Using the data for calcu ...

Find and return a specific record from MongoDB if it matches the exact value

model.js import mongoose from 'mongoose'; const { Schema, Types } = mongoose; const participants = { user_id: Types.ObjectId(), isAdmin: Boolean } const groupSchema = new Schema({ id: Types.ObjectId(), // String is shorthand for {type: St ...

Issues with the Click Event on Angular Calendar

I am currently using the angular calendar from the GitHub repository https://github.com/10KB/angular-clndr but I am facing an issue with my click event not working, even though I have copied the code exactly as shown in the link. If there are any setup st ...

Marshaling a payload in Groovy at a snail's pace

I am currently working on an Angular/Groovy Application and facing slow performance while marshaling a payload in the backend (Groovy). The process takes a significant amount of time to complete, send the data to the frontend, and render it. In the backen ...

Creating a Next.js dynamic route that takes in a user-submitted URL for customization

Currently, I have implemented the Next.js Router to facilitate the display of different dashboards based on the URL slug. While this functionality works seamlessly when a button with the corresponding link is clicked (as the information is passed to the Ne ...

Steps to successfully retrieve an image using JavaScript on the client side while circumventing any CORS errors

I have a React application where I am displaying an image (an SVG) and I want the user to be able to download it by clicking on a button. The image is stored in Firebase Storage. However, I am encountering an issue with CORS error: Access to fetch at &ap ...

How to efficiently eliminate duplicates from an array list using React framework

Keeping the array name constant while duplicating and repeating this process only clutters the list. Appreciate your help. setListItems(contents.data); console.log(contents.data); ...

Converting HTML table text to JSON data using vanilla JavaScript (without any external libraries like Selenium)

As a newcomer to programming and Javascript, my goal is to use Selenium Webdriver in Visual Code to extract HTML table content from a webpage and convert it into JSON data. I've managed to retrieve the table data, but I'm struggling with the conv ...

Create a Vue slot layout that mirrors the structure of Material UI

This is the code I have been working on: <tr :key="index" v-for="(item, index) in items"> <td v-for="header in headers" :key="header.value"> {{ item[header.value] }} </td> <td> & ...

Utilizing Google Tag Manager to save the identifier of a selected div or button

After searching high and low, and reading extensively, I still couldn't find the answer... I am managing a website where Google Tag Manager is in place, and I am trying to retrieve the ID of a clicked button (or its parent). This is my code snippet: ...

Explore a JSON structure and identify the parent key of a specific key:value pair

I may be new to coding, but I've hit a roadblock and can't seem to find the solution - despite numerous attempts on Google and StackOverflow. Behold, a JSON object: const json = { "catalog:aardvark": { "severity": "minor" }, ...

React Native - useEffect causing a double render on Home screen

I am facing an issue where my functional component "Home" keeps rendering again after I receive data from a function in the "useEffect" hook. If I use the "set" statement to store the data from the function in a const, it triggers a re-render of the Home c ...

What is the process for modifying the logfile path in phantomjs using selenium?

Is there a way to modify the default --webdriver-logfile parameter that selenium passes to phantomjs when using them together? This is the line in the selenium log: 11:06:06.960 INFO - arguments: [--webdriver=14380, --webdriver-logfile=<ROOT PATH DELE ...