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

I'm experiencing some issues with my scene in ThreeJS - the HDR background isn't displaying, and my cube

<style> body { margin: 0; } </style> <script async src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afcadc82c2c0cbdac3ca82dcc7c6c2dcef9e8199819c">[email protected]&l ...

Concealing a block from top to bottom

I currently have a filter that is hidden when clicked, with a transition effect that moves it from the bottom to the top. I have recorded my screen to demonstrate this behavior: . However, I now need the filter to hide from top to bottom instead, essenti ...

React Timer App: The setInterval function is being reset after each render operation

I'm currently working on a straightforward timer application that will begin counting seconds when a button is clicked. To implement this, I am utilizing react hooks. import React, { useState } from 'react' function Timer() { const [sec ...

retrieving information from an AngularJS $q promise

I'm currently working on a series of promises for sequential http GET requests. Imagine sending a cooking recipe to the server one step at a time, in order, just like following a recipe to bake a perfect pie. The final step will return the result; in ...

What is the best way to restrict the degree of camera rotation in the left, right, up, and down directions in Three.js when using a

Although this question may have been asked before, I haven't been able to find a solution to my specific issue! I've set up a 3D canvas using WebGLRenderer, PerspectiveCamera, and OrbitControls. My camera's position is at 0, 10, 500 for the ...

Is there a way to integrate a JQuery plugin into another plugin seamlessly without causing any conflicts or disruptions?

With the code provided, a flip effect is being generated using the JQuery Flip plugin. Within the "verso" property, there is a select menu with the ID #ddlBookletType, which triggers another JQuery plugin that creates dropdown menus. The current HTML stru ...

The designated function name can be either "onButtonClick" or "onClickButton"

I am a Japanese developer working on web projects. Improving my English language skills is one of my goals. What would be the correct name for a function that indicates "when a button has been clicked"? Is it "onButtonClick"? Maybe "onClickButton"? Co ...

Receiving the latest global variable in JavaScript using jQuery

I keep receiving undefined type for: $(".ui-slider-handle").attr("title", '"'+current+'"'); Even though I can successfully alert the updated value of current on line 29, it seems to not be working with .at ...

Looking to transition from Node.js version v4.4.5 to v6.11.0 on your Windows system?

npm cache clean npm update -g I attempted upgrading using the provided commands, but unfortunately, the update did not go through as expected. Seeking advice for a successful update process. (Currently on Node.js 4.4.5 and aiming to upgrade to Node.js 6. ...

Using a different method to handle multiple callbacks in Angular or a suitable replacement for $.Callbacks

Is there a similar functionality in Angular to jQuery $.Callbacks? I am seeking a straightforward method to manage callback lists within Angular. My goal is to achieve the following using Angular: function Broadcast(){ var self= this; this._status ...

Verify if a certain value exists in an array while using ng-if inside ng-repeat

Currently, I have a loop using ng-repeat that goes through a list of wines obtained from an API. Alongside this, there is an array variable containing all the IDs of wines that have been marked as favorites and retrieved from the database. My goal is to sh ...

Is there an Angular counterpart to Vue's <slot/> feature?

Illustration: Main component: <div> Greetings <slot/>! </div> Subordinate Component: <div> Planet </div> Application component: <Main> <Subordinate/> </Main> Result: Greetings Planet! ...

Filtering data in Vue.js using JSON specifications

How can I display only the names in the data? I currently have cards filtered by cities <div v-for="item in stationCityData"> <div v-for="option in filteredCity" style="background:#eee;padding: 20px"> <!-- <div v-for="option ...

What is causing the slow performance of this JavaScript array retrieval?

I am working with a large array called frames_to_boxes, consisting of 5000 elements. Each element is an array of Objects belonging to the Box class: class Box { constructor(x, y, width, height, frame, object_class, id) { this.x = x; this.y = y; ...

Tips for presenting hierarchical information from my database in ejs

I'm currently working on a genealogy application using node js express and ejs but I'm facing an issue with displaying the database in order (starting from parent). This is the code snippet for retrieving my data and what I see when I log the ou ...

In an empty JavaScript MVVM Organization View, the ViewModel is packed with lines of code

I find myself always placing all of my code within the ViewModel because nothing else seems to fit. What kinds of things should be included in the view? Does anyone have any examples? ...

The Ajax database browser page refresh feature updates the content without actually refreshing the entire page

I am encountering an issue with my AJAX and PHP database integration. I believe many novice Ajax programmers are facing a similar problem. Despite shortening the code, it remains lengthy so please bear with me. There's a button on the homepage index.p ...

Utilizing AngularJS ng-show to conditionally display content based on data retrieved from an

I am facing an issue with implementing the ngShow directive in my code, where I am trying to display data fetched from an API call. However, despite everything else working correctly, the ngShow directive does not seem to be functioning as expected. Here ...

Submitting HTML form data to a Java class via JavaScript, following validation with JavaScript within a JSP file

I am struggling with posting data obtained from an html form created in a jsp file using javascript and sending it to a java class after validating the form data. I was exploring alternatives to Ajax since I am not well-versed with those tools, but if you ...

Uncertainty arises from the information transmitted from the controller to the Ajax function

In one of my coffee scripts, I have an AJAX call that calls a method in a controller. The AJAX call is structured like this: auto = -> $.ajax url : '<method_name>' type : 'POST' data : <variable_name> ...