Implementing dynamic addition and removal functionality in AngularJS using ng-repeat and ng-model

In the process of creating a dynamic form with add/remove functionality, I experimented with utilizing ng-model within ng-repeat. Here is an example of what my code entails:

<button ng-click='add()'>Add more</button>
<div ng-repeat='x in array track by $index'>
    <input ng-model='array[$index].name'></input>
    <input ng-model='array[$index].phone'></input>
    <input ng-model='array[$index].email'></input>
</div>

//angular module
$scope.add = function () {
    $scope.array.push(item);
};

However, this approach resulted in all input fields being synchronized and displaying identical content for each item in the array, which was not my intended outcome. For reference, a working sample of my code can be found on codepen.

Answer №1

Essentially, the issue is that you are continuously adding a reference to the same "item" in the list, resulting in multiple references pointing to one item.

A better approach would be to:

angular.module('myapp', [])
.controller('Ctrl', ['$scope', '$compile',function ($scope, $compile) {
  $scope.array = [];
  var item = {
    name: '',
    phone: '',
    email: '',
  };

  $scope.array.push(item);
  $scope.addItem = function () {

    $scope.array.push(
      {
        name : '',
        phone: '',
        email: '',        
      }    
    );

  };
}]);

This revised version should resolve the problem. As for the HTML aspect, many prefer using ng-repeat in a simpler manner like this:

<div ng-repeat='x in array'>
    <input ng-model='x.name'></input>
    <input ng-model='x.phone'></input>
    <input ng-model='x.email'></input>
</div>

Answer №2

By pushing `item` in each iteration, you are essentially adding a reference to the same object multiple times. This means that any changes made to one instance of `item` will reflect on all elements in the array since they all point to the same object.

To resolve this issue, a simple solution is to add a copy of `item` instead of `item` itself within the $scope.add() function:

$scope.array.push(angular.copy(item));

An even better approach would be to define `item` as an object and instantiate it as needed:

var Item = function (){
    return {
        name: '',
        phone: '',
        email: ''
    };
};

Then, you can push new instances of `Item` into the array like so:

$scope.array.push(new Item());

Answer №3

Revise your JavaScript code like this:

angular.module('myapp', [])
.controller('Ctrl', ['$scope', '$compile',function ($scope, $compile) {
  $scope.entries = [];

  var entry = {
    name: '',
    phone: '',
    email: '',
  };

  $scope.entries.push(entry);
  $scope.addEntry = function () {
    entry.name = $scope.name;
    entry.phone = $scope.phone;
    entry.email = $scope.email;
    $scope.entries.push(entry);
    $scope.name = "";
    $scope.phone = "";
    $scope.email = "";
  };
}]);

Ensure that each of the name, email and phone are stored in separate models.

When adding an item to the array, remember to reset them.

Also update the model names in the HTML.

View the changes here.

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

Locate all buttons on the page that have an onclick function attached to them, and

I seem to have run into an issue. I am currently working with Java and WebDriver. My goal is to navigate to , locate the item "ipod", receive 4 results, and then compare them by clicking on the "compare" button beneath each item. However, I am encounteri ...

Refresh Div/PartialView periodically

I have a function that performs an Ajax call, retrieves a result, and functions perfectly. @foreach (var fighter in Model.Fighters) { @Ajax.ActionLink(fighter.FirstName + " " + fighter.LastName, "ShowResults",new {id = fighter.FighterID }, new AjaxOptions ...

Unleashing the Power of Aurelia's HTML Attribute Binding

I need to bind the "required" html attribute in my template and model. Along with passing other information like the label value using label.bind="fieldLabel", I also want to pass whether the element is required or not. However, simply using required="tr ...

Angular (TypeScript) time format in the AM and PM style

Need help formatting time in 12-hour AM PM format for a subscription form. The Date and Time are crucial for scheduling purposes. How can I achieve the desired 12-hour AM PM time display? private weekday = ['Sunday', 'Monday', &apos ...

Develop an asynchronous function that can fetch a result at a later time within an Express route

I need to retrieve an Excel file from Box.com using their API and then convert the Excel data into JSON format. Afterwards, I plan to display this JSON data using Express and Handlebars. Below is the function I've created for fetching the Excel file ...

Best practices for effectively managing errors within JSON web tokens

I am a novice attempting to manage JWT verification. Within the function below, my goal is for the system to generate a new access token based on the refresh token if the user's access token has expired. import { asyncHandler } from "../utils/asy ...

Wait for Axios Request Interceptor to complete before sending another ajax call

One feature I have added is a request interceptor for all axios calls. This interceptor checks the JWT token and automatically refreshes it if necessary. axios.interceptors.request.use((config) =>{ const currentState = store.getState(); // get upd ...

What are your thoughts on Uptrends vs Dynatrace for Website Monitoring?

I'm seeking recommendations for improving monitoring on a retail website. Any advice would be appreciated. Thank you in advance. ...

JavaScript Regular Expression Assistance Domain Snatcher

I am in the process of developing a JavaScript Regex and I am struggling to find the right pattern to match a specific domain. Let me provide an example for better understanding. I need a regex that can identify any domain that exclusively contains (text. ...

Unsubscribe option in the AWS Software Development Kit for Node.js

Is there a way for me to include a List-Unsubscribe : <mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcdddedffcdfd8da92dfd3d1">[email protected]</a>> header in my outgoing email message while using A ...

Conceal and unveil stationary navigation when scrolling back to the very top of the screen

My current setup includes a navigation that dynamically hides as the user scrolls down and reappears when scrolling up. Additionally, I have applied the class .fixed on #top-wrapper to alter the layout/styling of this specific div. However, I am facing dif ...

What is the best way to serve index.html from a Node.js/Express application?

I am attempting to serve the index.html file from my node/express app, but I am encountering some difficulties. This is my server.js: const express = require('express'); const path = require('path'); const http = require('http&ap ...

The technique of working through a recursive promise in an iterative manner

Trying to implement a promise function calling from its own response with the following pattern: f().then(function(response){ if(response){ f(response).then(function(response){ if(response){ f(response).then..... ...

Customize the height of the Angular Material autocomplete dropdown to meet your needs

Context I have been working on a customized autocomplete feature using Angular Material, and I need to adjust the height of the dropdown results box for better visibility. Exploration After conducting some research, I discovered that Angular Material cu ...

Utilizing a JSON object named "shop" to populate a grid within a fresh ExtJS window

Similar to this Stack Overflow question, my issue involves loading JSON data into a new window. I want the structure of the new window to be like this example. The challenge is combining the solutions for reading JSON and creating a grid in a new window, ...

Displaying a plethora of data points on a single graph using jQchart with a

I'm currently using jQchart to showcase a graph, but I'm running into an issue with the title property only displaying a single line of text. The current title being displayed on the graph is as follows: text: chartTypeText + ': ' + ch ...

What is the best method for ensuring that cheese rises to the top?

Is there a way to increase the value of the variable cheese? I suspect it has something to do with how the variable cheese is defined each time the JavaScript is activated, but I'm not sure how to go about it. Can you offer some guidance on this? & ...

Executing code after finishing a fetch in Next.js

Here is the JavaScript code snippet under question: async function checkAuth() { console.log("3") await fetch(apiUrl+'/auth', { method: 'POST' }).then(response => response.json()).then(result => { ...

How to display a list of buttons with unique names using ng-repeat in Ionic 3

Just starting out with Ionic 3 and attempting to create a list of buttons using ng-repeat. Each button differs only in name. Here's my HTML code: <ion-content padding> <div ng-repeat="tip in healthTipsButtonList"> <button i ...

Encountering Uncaught Syntax Error when attempting a request with JSON parameters

Currently, I am using Fetch to send a post request to my server while including some additional information. Here's the code snippet: var rating = document.getElementById("rating"); var ratingValue = rating.innerHTML; fetch("/films",{ method: "po ...