Saving multiple rows in AngularJS by extracting data from ng-repeat and storing it efficiently

Greetings! I am fairly new to AngularJS and currently grappling with a concept...

Essentially, I have a form that can accommodate 1 to many "Guests" for an event. By utilizing ng-repeat, I showcase the fields in this manner:

<div ng-repeat="guest in guests">
  <input type="text" ng-model="guests[$index].first_name" />
  <input type="text" ng-model="guests[$index].last_name" />
  <select ng-model="guests[$index].meal" ng-options="meal.id as meal.name for meal in meals"></select>
  <select ng-model="guests[$index].rsvp">
    <option value="0">No</option>
    <option value="1">Yes</option>
  </select>
</div>
<div class="controls"><button ng-click="submit()" class="btn btn-success">Save</button></div>

Furthermore, in the controller:

  //DETERMINE TOTAL IN PARTY
  var totalInParty = 2;
  $scope.meals = RSVPRes.Meals.query();

  //EDIT
  if ($scope.rsvpId) {
  }
  //NEW RSVP SUBMISSION
  else {
    $scope.rsvp = new RSVPRes.RSVP();
    //INITIALIZE EMPTY GUESTS
    $scope.guests = [];
    for (var i = 0; i < totalInParty; i++) {
      $scope.guests[i] = {
        first_name: '',
        last_name: '',
        meal: 1,
        rsvp: 0
      };
    }
  }

Moreover, here is my Resource setup:

.factory( 'RSVPRes', function ( $resource )  {
  return {
    RSVP: $resource("../reservations/:id.json", {id:'@id'}, {'update': {method:'PUT'}, 'remove': {method: 'DELETE', headers: {'Content-Type': 'application/json'}}}),
    Meals: $resource('../meals.json')
  };
})

Everything seems to be functioning smoothly, however, saving the data poses a challenge. My aim is to save each Guest's details (First Name, Last Name, Meal & RSVP) as individual rows.

When attempting the following:

$scope.submit = function() {
  for(var i = 0; i < $scope.guests.length; i++){
    $scope.rsvp.first_name = $scope.guests[i].first_name;
    $scope.rsvp.last_name = $scope.guests[i].last_name;
    $scope.rsvp.meal_id = $scope.guests[i].meal;
    $scope.rsvp.rsvp = $scope.guests[i].rsvp;
    $scope.rsvp.$save();
   }
   $state.transitionTo('rsvps');
 };

This results in creating two rows (with total_in_party set to 2) but always containing the data of the second person.

I feel like I'm on the right track, I've explored several ng-repeat examples but none seem to address my specific scenario!

Any assistance would be greatly appreciated.

SOLVED

I had made an error in my approach towards the Resource, by creating a new RSVP object every time within the loop.

$scope.submit = function() {
  for(var i = 0; i < $scope.guests.length; i++){
    $scope.rsvp = new RSVPRes.RSVP();
    $scope.rsvp.first_name = $scope.guests[i].first_name;
    $scope.rsvp.last_name = $scope.guests[i].last_name;
    $scope.rsvp.meal_id = $scope.guests[i].meal;
    $scope.rsvp.rsvp = $scope.guests[i].rsvp;
    $scope.rsvp.$save();
   }
   $state.transitionTo('rsvps');
 };

Answer №1

Transfer the $scope.rsvp.$save(); statement outside of the loop

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

Error Encountered: Unable to Locate 'bootstrap' label in Bootstrap 5 Popover

I have been working on implementing a popover in my Angular 12 project using Bootstrap version v5.0.1. However, I am encountering a name error that I can't seem to resolve: var exampleEl = document.getElementById(item.name + index); var tooltip = ne ...

Capture various data points in an array with each click

I am currently working on a menu of buttons where users can select multiple options at the same time. My goal is to record all selected buttons in one array instead of individual arrays for each button. The end result I hope to achieve is an array like t ...

What steps should I take to resolve the "StrictMode has found deprecated findDOMNode" error?

Whenever I trigger the button to open the drawer, my console displays the warning message '' findDOMNode is deprecated in StrictMode'' The container for the button component is called Sidenav import Sidenav from './Sidenav'; ...

What do you prefer: defining properties with the JSON object or with objectName.property in JavaScript

Can you tell me which approach is considered the best practice? Is it better to use the "this" statement in the following way: var obj = { x: 20, y: 10, width: this.x, height: this.y, render: function () { // renders object on canvas ctx.fi ...

Encountering a problem with npm reading dependencies

I decided to kickstart a new Node application by following a tutorial and creating a package.json file. Below is the content of my json file: { "name": "Dashboard", "version": "0.0.0", "description": "Client-A Dashboard", "dependencies": { ...

Running a Node JS application concurrently with an Express API connected to MongoDB

Here's my current project plan: I've created a small Node app that fetches data about the stock market from an API and then stores the data in a Mongo DB (which is already up and running). My next step is to create an API that will allow other se ...

Unitary Individuals and the Connection Automation

It is advised to refrain from using the deprecated com.sun.star.frame.Desktop type and opt for the com.sun.star.frame.theDesktop singleton instead. Various programming languages provide access to singletons. For instance, in Java, this thread mentions the ...

Guide on calculating the total sum of numbers from multiple selected elements based on class within a div that has a designated id

https://i.sstatic.net/uyjPk.pngI'm currently working on a task that involves summing up the number of listeners from various servers. These values are stored within a div with the id="channel1", and each number of listeners is located in a span elemen ...

What is the best way to fetch information from an API using Angular5 with Material2 components?

Here are the 'table.component.html' and 'table.component.ts' files where I am pulling data from an API to display in a table. Below is the object received from the API: [ {position: 1, name: 'Hydrogen', weight: 1.0079, sym ...

Exporting an Excel sheet cell with a specific date format

When exporting an empty excel sheet with header values, I need to set the date format (mm/dd/yyyy) for a specific cell in the sheet. How can I achieve this? Below is how I have defined the cells in the excel sheet: var InstructionSheet = workbook.add ...

Using PHP to send asynchronous requests to the server can greatly enhance

I have almost completed my project, but I am facing an issue with reading the data sent to the server. function main() { jQ(document).on("keyup", "form input", function () { var data = new FormData(); var value = jQ(this).val(); da ...

Constructor function fails to display accurate outcomes

Just beginning my coding journey here. Attempting to create a car object and its instances. Here's the code snippet: function Car(name, speed) { this.name = name; this.speed = speed; this.describe=describeCar; }; f ...

ng-Pattern in AngularJS

Enter a number as your username in the field below: <fieldset class="col-sm-12 col-xs-12 text-center"> <label for="username">Username</label> <input type="text" id="username" ng-pattern="/^[0-9]*$/" ...

JavaScript's concise ternary operation can be used for quick if/else statements when conducting

Here is my current if/else setup: async invoke(request, response) { const { deleted } = request.query; let users = []; if (deleted === 'true') { users = await User.findAndCountAll({ where: { ...

Component fails to trigger @click handler

.vue component <template> <div class="modal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> Loading Files </div> < ...

AngularJS allows you to dynamically update a list by adding elements to the end as

I have a specific requirement to showcase a lineup of elements in a single row, granting users the ability to scroll through them. Upon reaching the end of the scroll, a function should be triggered to add more elements to this lineup. I've successfu ...

The Highchart is failing to display a single data point

The marker I set is not displaying when there is only a single data point available. The data point is only showing up when we hover on the chart. Check out an example fiddle here - jsfiddle ...

Integrating external JavaScript widgets into the web application in real-time

I am currently engaged in a React js project that involves the dynamic addition of third party scripts (widgets) to the web app. These widgets encompass various third party platforms such as Twitter, Instagram, Youplay, Youtube, and more. The existing co ...

Generating an image id upon click in ReactJS

Below is the code designed to showcase a collection of images on a webpage with React JS: this.displayedImageList = this.imageResults.map(function(picture){ return <div className="galleryBox" key={picture.toString()}><img src={picture} alt="I ...

What is the best way to run a JavaScript function once another function has finished executing?

I am looking to ensure that a JavaScript function runs only after another one has finished executing. Here is the code I currently have: $(window).load(function(){ $('#dvLoading').fadeOut(2000); }); window.addLoadEvent = function() { $('#p ...