Store a collection of student items in the database using AngularJS

Seeking assistance as I delve into learning angularjs. While I have figured out how to save one item to a database, my goal is to take it a step further and save multiple items. Unfortunately, my searches online have not yielded any results on how to accomplish this with angularjs. Is it even possible to achieve this in angularjs? To better illustrate my query, I have included the code on Plunker.

http://plnkr.co/edit/sF3mBOcDilhQDQKYqeE7?p=preview

script.js

var app = angular.module('multi', []);
app.controller('MainCtrl', function ($scope) {
    $scope.students = [{
        'firstname'  : $scope.user_name, 
        'lastname' : $scope.lastname,
        'bday':$scope.bday,
        'bplace':$scope.bplace,
        'sex':$scope.sex
     }];

$scope.addNewStudent = function() {
var newItemNo = $scope.students.length+1;
$scope.students.push({'id':'student'+newItemNo});
};

$scope.removeStudent = function() {
var lastItem = $scope.students.length-1;
$scope.students.splice(lastItem);
};

$scope.save = function() {
    $http.post('db.php?action=addStudent', 
       {
        'firstname'  : $scope.firstname, 
        'lastname' : $scope.lastname,
        'bday':$scope.bday,
        'bplace':$scope.bplace,
        'sex':$scope.sex

    });
};
});

After entering the information for each student, I aim to click the save button to store all students in my database. If this is indeed achievable, can you provide guidance on this matter? Thank you.

Answer №1

The challenge here is that you're relying on values from the $scope for saving, which limits your ability to save multiple students at once.

To address this, utilize the existing $scope.students array.

I've made some adjustments to your plunker (specifically in the javascript) to cater to your needs.

Check out the modified version of your plunker here.

The changes I made mainly involve placing the $http.post within a loop. While I usually recommend using a server route for handling multiple objects, I opted for a simpler and functional approach due to limited information about your server setup.

Furthermore:

  • You're sending the student.sex to the server even though it's not part of the form input.
  • Inconsistency noticed between last in the html form and lastname in the save function. Choose one naming convention and stick with it across both elements.

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 is the best way to execute multiple Protractor test suites simultaneously?

Exploring Protractor for the first time. My goal is to run multiple test suites in a sequence. I have a complex angular form with various scenarios, each with its expected results. I want to execute all tests with just one command. Initially, I tried enter ...

Improving Vue Component on Navigation

I am facing an issue with my navbar where I have two versions. Version 1 features a white text color, while Version 2 has black text. The need for two versions arises due to some pages having a white background, hence the requirement for black text. Bot ...

Tips for adding a border to an element when hovered over

I am looking to achieve a hover effect that displays a border around an element without actually adding the border to the element itself, as shown in this image: https://i.sstatic.net/iFpCA.png The challenge I'm facing is that I want to allow users ...

Integrate the dForm plugin with a convenient time picker widget

Currently, I am attempting to integrate a time picker widget into a jQuery plugin called dForm. The specific timepicker widget can be found at the following link: https://github.com/jonthornton/jquery-timepicker Despite reviewing the dForm documentation, ...

A fatal error has occurred in Node as it is unable to set headers after

Just getting started with nodeJs and I'm attempting to read a file from the system. It seems like I can view the file content in the console, but for some reason it's not displaying in the browser. Any ideas what I might be overlooking? var myD ...

Show only the objects in a MongoDB collection that have a matching status in another collection

I have two different collections - one called competition and the other called product. The competition collection contains the objectID of the product, while the product collection contains the competition_status. My goal is to only display the competiti ...

The testcafe selector fails to locate any 'div' elements

I've encountered a strange issue with testcafe. When testing one of my websites, I'm unable to select div elements, but I can select other types of elements without any problem. For example: await t.click(Selector("span").withAttribute( ...

The error encountered at line 8 in the file ui-bootstrap-tpls-0.14.3.min.js is: "Uncaught ReferenceError:

Everything was working perfectly in my application until I decided to install ui-bootstrap-tpls-0.14.3.min.js I added ui.bootstrap as a dependency like this: var app = angular.module("earnfitApp", ['ngRoute','ui.bootstrap']); I made ...

I am looking to transmit information to the controller using AJAX

ajax console.log(total);//10 console.log(number);//4 var form = { total:total, number:number } $.ajax({ url: 'items/cart/update', type: 'POST', data:form }); Spring MVC controller @ResponseBody @P ...

What is the best way to include a collapsible submenu in a dropdown menu

Is there a way to incorporate a collapse menu into a dropdown menu? The desired functionality is for the dropdown menu to close when clicking on a menu item with collapse, and then have the collapse feature work again when reopening the dropdown menu. & ...

Creating a table and populating its cells with values all within the confines of a single function

This section of code aims to create 3 arrays by extracting values inputted by the user from a popup menu in the HTML file. These values are then utilized to populate the table displayed below. var arrM = new Array; var arrT = new Array; var ar ...

The occurrence of Multiple Button events leads to an error message stating: "Uncaught TypeError: Cannot read property 'remove' of undefined"

I am struggling to add an EventListener to each Delete Button (1,2,3) as I keep encountering an error that says "add" is undefined. Do you have any suggestions on how to fix this issue? My goal is to display a confirmation window when the DELETE button is ...

Interfacing Highcharts with Angular for seamless data binding across series

I am fairly new to using highcharts and I am having difficulty binding my data into the series parameter. In my controller, I have an array of objects that I want to display (when I use console.log, I can see that they are all properly there) this.plotDa ...

What is the best way to minimize the number of requests sent in AngularJS?

Currently in my demo, each time a user types something into an input field, a request is sent to the server. However, I would like only one request to be fired. For example, if the user types "abc," it currently fires three requests. Is there a way for the ...

Tips for utilizing the verticesNeedUpdate feature in threejs for refreshing the vertex positions of a 3D cube

let geometry = new THREE.BoxGeometry(500, 500, 500); scene.add(geometry); let edgesGeometry = new THREE.EdgesGeometry(geometry); scene.add(edgesGeometry); let material = new THREE.LineBasicMaterial({ color: 0xffffff, linewidth: 2 }); scene.add(material); ...

Detecting changes in arrays in Vue.js 2

Below is a simplified version of the code : <template> /* ---------------------------------------------- * Displaying a list of templates, @click to select the template /* ---------------------------------------------- <ul> ...

Customizing React components based on API data

const LinkList = () => { const [links, setLinks] = useState([]); const url = 'http://localhost:5000/xyz'; const hook = () => { console.log('effect'); axios .get(url) .then(respo ...

NodeJS: Updating MySQL Database Following a Successful Paypal Transaction - A Step-by-Step Guide

Looking for guidance on updating the mySQL database following a successful Paypal transaction using NodeJS. I'm uncertain whether to execute the insert into the database statement in app.js or server.js. My setup involves running server.js during lau ...

Tips for maintaining a variable's persistence through Heroku dyno/server restarts and fresh deployments

I need to find a way to persist the values in an array through dyno restarts and code deployments on my Node.js server. The issue I am facing is that every time the server restarts, the 'arrayWithValues' array gets reset to empty. Below is the se ...

If the item with the specified name is not found in the list, display an image using Vue's v-if directive

<ul class="ulItems" v-for="item in listingItems" :key="item.channels"> <li class="liItems"> {{ item.itemName }} </li> </ul> I am looking to incorporate an image in situations where th ...