obtaining information from newly added form elements in an Angular application

I'm currently working on an app with the MEAN stack. I've managed to dynamically add form elements, but I'm running into an issue where all dynamically added elements are taking the same data when I use ng-model="something.something". What I really want is to store the data as objects inside an array. Any help would be greatly appreciated.

Below is my HTML code:

  <div layout-gt-sm="row" ng-repeat="(key,aca) in vm.academic">
                <md-input-container class="md-block" flex-gt-sm>
                    <label>Degree</label>
                    <input name="degree" ng-model="vm.academic[key].degree">
                </md-input-container>
                <md-input-container class="md-block" flex-gt-sm>
                    <label>University/Board</label>
                    <input name="university" ng-model="vm.academic[key].university">
                </md-input-container>
                <md-input-container class="md-block" flex-gt-sm>
                    <label>Percentage/Grade</label>
                    <input name="grade" ng-model="vm.academic[key].grade">
                </md-input-container>
            </div>
            <div layout="row" layout-align-gt-sm="end">
                <md-button class="btn1" aria-label="add button" ng-click="vm.add();">
                    <md-icon md-svg-icon="plus"></md-icon>
                    <md-tooltip md-direction="top">
                       Add more field
                    </md-tooltip>
                </md-button>
            </div>

And here is my JavaScript code:

   vm.academic = [{}];
   vm.add = add;

    function add() {
    console.log('button clicked');
    vm.academic.push({
        degree:'',
        university:'',
        grade:''
    });
};

I'm struggling to figure out how to set different ng-models for each field so that I can save the data in a database. Any suggestions?

Answer №1

If you're looking to properly format your HTML, here is the code snippet that can assist you:

 <form name="FormName" novalidate>
        <div layout-gt-sm="row" ng-repeat="aca in vm.academic">
            <md-input-container class="md-block" flex-gt-sm="">
                <label>Name</label>
                <input type="text" ng-model="aca.name" >
            </md-input-container>
            <md-input-container class="md-block" flex-gt-sm="">
                <label for="email">Email Id</label>
                <input type="email" ng-model="aca.email"/>
            </md-input-container>
        </div>
    </form>

To initialize vm.academic = [{}]; in your controller and create add and remove methods like this:

vm.addNewAcademic = function(){
   vm.academic.push({});
};
vm.removeAcademic = function() {
   var num = vm.academic.length-1;
   if ( num !== 0 ) {
      vm.academic.pop();
   }
};

You will receive an output result similar to

[{'name':'a','email':'bb'},{'name':'c','email':'dd'}]

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

Closing a live search box by tapping away from it

The link I found as the best example for this topic is: http://www.example.com In the example provided, if you enter a keyword in the search field, suggestions will drop down. I have implemented this code but would like to make a slight modification. I w ...

Choose checkboxes based on the checkboxes that were previously selected

My goal is to have a checkbox automatically selected based on the previously selected checkbox. For example, if I select the first checkbox (which has a specific class), then only the checkbox with the same class as the first one should be selected using j ...

Angular TypeScript state management system

I am facing a challenge in connecting a controller to a state (using angular ui.router) where one way of writing it works, while the other does not. Successful example (with the controller registered under the module): this.$stateProvider .state(' ...

Why is the `node-config` configuration undefined within a TypeScript Jest environment?

I have a TypeScript module that is functional in both development and production environments. It utilizes https://github.com/lorenwest/node-config. When I attempt to import it into Jest for testing purposes, I encounter an error suggesting that the config ...

The error message "no match found" can only occur on the server-side when using jQuery version 1.x

Having an issue with this small section of code: $('.desc_container').each(function() { var fulltext = $(this).text(); if(fulltext.length > 50) { var myRegexp = /^(.{47}\w*\W)(.*?)$/g; var match = myRegexp.exec(f ...

Can dynamic CSS imports be unloaded in a React application?

I am facing an issue with loading two files using react.lazy and suspense: import React, { Suspense, lazy } from "react"; import { Route, Redirect } from 'react-router-dom'; const MainLayout = lazy(() => import('Components/Layout/MainL ...

Transforming an array of flat data into a hierarchical tree structure

I'm facing a challenge with my script. I have an Array of FlatObj and some rules, and I need to create a converter function that transforms them into TreeObj. The Rules are: If an object has a higher depth, it should be a child of an object with a l ...

Fire an event following the execution of $state.go()

Is there a way to activate an event once the state has been modified in ui.router? Specifically, I am utilizing the ionic framework alongside angularJS which incorporates angular-ui-router. Note: Below is the pseudo code I am hoping to implement. $state. ...

Tips on implementing v-show within a loop

Hey @zero298, there are some key differences in the scenario I'm dealing with. My goal is to display all the items in the object array and dynamically add UI elements based on user input. Additionally, v-if and v-show function differently (as mentione ...

Express npm dependency fails to start globally

I have recently reinstalled my operating system from Windows 8.1 to Windows 8.1, and I have been using npm for quite some time. Previously, it was working fine as mentioned here. After the reinstallation, I tried installing npm i -g express, but it does n ...

Initiate and terminate server using supertest

I've developed a server class that looks like this: import express, { Request, Response } from 'express'; export default class Server { server: any; exp: any; constructor() { this.exp = express(); this.exp.get('/' ...

Combining Date and Time in Javascript: A Guide

As a JavaScript beginner, I am struggling with combining date and time pickers. Despite finding similar questions, I have not yet found the solution I need. I have two inputs: one for the datePicker and another for the timePicker. <form> <div clas ...

Testing the Angular module's run function with unit tests

For our project, we have implemented requirejs along with angularjs. Our main application module is named 'app' and we have separate modules for services (app-services), controllers (app-controllers), filters (app-filters), etc. These modules are ...

JavaScript: How to identify and select a specific item from a context menu

Currently diving into the world of JavaScript, so please keep that in mind when explaining. My main goal is to figure out a way to detect when a user triggers a right-click or uses the context menu from the keyboard. Specifically, I want to know if they s ...

How to retrieve a form submission from Jquery HandsonTable in PHP using $_POST

Recently, I've started diving into the world of javascript/jquery/ajax. My current project involves fetching data from a jQuery handsonTable () and integrating it with my PHP code. The process includes generating a table from a MySQL database, utili ...

How does the onclick event trigger even without physically clicking the button?

I am struggling with creating a simple button using mui. My intention is to activate a function only when the button is clicked, but for some reason, as soon as I enter the webpage, it triggers an alert automatically. This behavior is puzzling to me and ...

Automated scrolling within a div when an li element overflows

Looking to implement automatic scrolling in a div. I have a list of elements within a fixed height div, and now I want the div to scroll automatically when I press the down key after highlighting the 3rd li element (i.e Compt0005). Can anyone help me solve ...

Experiencing trouble with calculating the total value of an array of objects due to NaN errors

I've been working on developing this web application in VUE.js, but I'm facing an issue with a specific function where I am attempting to sum the values of each object within an array. This is resulting in a NaN (Not a Number) error. Let's t ...

Determine the daily volume of emails sent from the "no-reply email" address using the Nodemailer library

Our company currently utilizes Nodemailer for internal email communication. Lately, we have been encountering issues with exceeding our daily SMTP relays, resulting in some emails failing to send. To investigate further, I have been tasked with monitoring ...

When the add button is clicked, I would like to implement a feature where a checkbox is added

When the user clicks on the link "출력하기", I want the web page to add a checkbox to all images. I wrote this code, but it's not working. Can anyone help me? This is my JS: $(document).ready(function(){ $("#print").on('click', fu ...