Creating duplicates of form and its fields in AngularJS with cloning

I'm facing an issue with a form that contains various fields and two buttons - one for cloning the entire form and another for cloning just the form fields. I attempted to use ng-repeat, but when I clone the form and then try to clone fields in the original form, it ends up cloning the fields in the duplicated form as well. How can I prevent this from happening? Below is my HTML code:

    <!DOCTYPE html>
    <html>
      <head>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcdcd3dac8d1dccf92d6cefd8d938b918c">[email protected]</a>" data-semver="1.6.1" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>
  <body>
    <div ng-app="myApp" ng-controller="MyController">
      <div ng-repeat="form in forms">
        <hr />
        <form name="myForm" ng-init="name = form.name">
          <br>

          <div ng-repeat="user in users">
          <input type="text" ng-model="user.name"/>
            <input type="text" ng-model="user.phone"/>
          </div><br>
          <button type="button" href="" ng-click="addUser()">Add user</button>
        </form>
      </div>
      <hr />
      <input type="button" value="Create form" ng-click="createForm()" />
    </div>
  </body>    
</html>

This is what my `script.js` looks like:

    angular.module("myApp", []).controller('MyController',
    ['$scope', function($scope){
    $scope.forms = [{name: "form1"}];
    $scope.createForm = function(){
        $scope.forms.push({name: "form" + ($scope.forms.length + 1)});
    };
    $scope.saveForm = function(formScope){
        alert("Save called for " + formScope.name + ", myInputValue = " + formScope.myInputValue);            
    };
     $scope.users = [{name: 'John',phone: '098097770'},{name: 'Alice',phone: '765876598'}];
  $scope.addUser = function() {
    $scope.users.push({name: 'New user',phone: ''});
  };
  $scope.submit = function() {
    alert('Here are the users: ' + angular.toJson($scope.users));
  };
}]);

You can view the Plnkr Demo here.

Answer №1

Check out this plnkr to see the solution in action: plnkr

The key is to establish a connection between the user and the form object, ensuring that each form has its unique identifier.

You'll need to make adjustments to the ng-repeat (nested) and add a function call for addUser, passing the index of the form where the user should be added.

$scope.forms = [
      {
        name: "form1",
        users: [
            {name: 'John',phone: '098097770'},
            {name: 'Alice',phone: '765876598'}
          ]
      }
    ];

$scope.createForm = function(){
        $scope.forms.push({
          name: "form" + ($scope.forms.length + 1),
          users: [
            {name: 'John',phone: '098097770'},
            {name: 'Alice',phone: '765876598'}
          ]
        });
    };
    
$scope.saveForm = function(formScope){
        alert("Save called for " + formScope.name + ", myInputValue = " + formScope.myInputValue);            
    };

$scope.addUser = function(index) {
    $scope.forms[index].users.push({name: 'New user',phone: ''});
  };

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

Showing JSX/HTML content depending on the props received

Can you identify the name of this type of expression and do you know in what scenarios it should be applied? {props.type === "big" && <h2>{props.title}</h2>} ...

Three.js Collada Loader struggles to load a small scene with multiple objects

While I am new to Three.js, the question I have is quite complex. I am working with a Collada scene in DAE format, which actually includes references to other DAE files. The structure of this "parent" file looks something like this: <library_visual_sc ...

A guide on how to perform a PUT or DELETE operation for Azure Table Storage using Node.js

I've been faced with a challenge in my project where I aim to create basic CRUD functionality for Azure Table Storage. However, I'm encountering difficulties in generating a valid SharedKeyLite signature. While I can successfully generate valid ...

Utilizing React.hydrate in conjunction with Vue: A Beginner's Guide

Wondering about a unique scenario here - I have a website built with Vue and now I aim to showcase a library I developed in React. In order to steer clear of server-side rendering (SSR), I can simply wrap ReactDOM.hydrate(ReactApp, document.getElementById( ...

Tips for merging conditional and data binding classes in AngularJS

In order to dynamically apply different classes based on expressions in your AngularJS templates, you can make use of the ng-class directive. Here is an example: <div ng-class="{'class1' : expression1, 'class2' : expression2}"> ...

What is the method for enlarging the width of the nvd3 chart timespan?

Click here In the Plnkr linked above, I have included the latest versions of d3 and nvd3 libraries. Upon initial viewing of the chart, you may notice that all the timespan ticks such as 09:00, 08:30, 08:00, etc., are overlapping on the left xAxis. The ti ...

Navigating the process of returning a list from an AJAX method to a view through a controller in ASP.NET MVC

I need to retrieve a list from my controller and pass it to the view. Currently, I have the following script: function fetchNames(_id, _name) { $.ajax({ type: 'Post', url: 'GetNames/', data: { id: _id, name: _name}, su ...

Rename multiple files in bulk

With 10000 files consisting of php, html, css, and png formats that are interconnected to operate the website's engine, I am looking for a way to perform bulk renaming in order to ensure proper functionality. Not only do I need to rename the actual fi ...

What is the best way to assign default values when destructuring interfaces within interfaces in TypeScript?

My goal here is to create a function that can be used with or without arguments. If arguments are provided, it should work with those values; if not, default values should be used. The issue I'm facing is that although there are no TypeScript errors ...

Preventing event duplication through clone() method

I've successfully duplicated my HTML elements using this JavaScript code, but I'm having trouble copying the events associated with the code. Can anyone provide a solution? <script type = "text/javascript" language = "javascript"> f ...

Issue with Angularjs not saving data in a specific field

I've encountered an issue trying to save data in the name field. Even though the POST request runs without any errors, the MongoDB collection only shows the _id and _v fields being updated. To put it simply, I'm unable to successfully save data ...

Keeping Chart.JS Up to Date: Updating Only Fresh Data

When a button is pressed on my website, a Bootstrap modal containing a Chart.JS is called. The data for this chart is loaded via an Ajax call as shown below: function loadReports(data) { $.ajax({ type: "POST", url: "Default.aspx/getRep ...

Wait for the scope value to become available before executing the directive or div

I have a unique directive created for SoundCloud that necessitates the SoundCloud URL. The URL is fetched from the database using the $http service, but the issue arises when the div for the directive is loaded before the URL value is defined. The code fo ...

Angular 13's APP_INITIALIZER doesn't wait as expected

Recently, I have been in the process of upgrading from okta/okta-angular version 3.x to 5.x and encountered an unexpected bug. Upon startup of the application, we utilized APP_INITIALIZER to trigger appInitializerFactory(configService: ConfigService), whi ...

Transform an array containing objects for convenient manipulation

I am attempting to manipulate an array using parse, push, and save data commands, but it seems like the code is not working properly. Can anyone offer assistance? I am very new to programming and just trying to improve my skills. The array should contain ...

Having trouble getting the expected transition effects to work with Vue.js

Currently, I have a display of lists of items through the use of v-for. Initially, only the summary section of each item is visible. Upon clicking on an item, the details section is supposed to appear. This functionality is achieved by adding or removing ...

Double array summation function

It is necessary for me to calculate the total coursePrice from this JSON data source here using AngularJS (javascript). I need to calculate two sums: one for each school and another for all schools combined. I have already displayed all the data in a tabl ...

A guide on effectively utilizing BehaviorSubject for removing items from an array

Currently, I am working on an Angular 8 application that consists of two components with a child-parent relationship. It came to my notice that even after removing an item from the child component, the item remains visible in the parent component's li ...

Can we utilize the elements in Array<keyof T> as keys in T?

Hello, I am trying to develop a function that accepts two parameters: an array of objects "T[]" and an array of fields of type T. However, I am encountering an issue when I reach the line where I invoke el[col] Argument of type 'T[keyof T]' i ...

How to Use Vue.js to Find the Nearest Div Element with a Specific

Below is the HTML code I am working with: <div id="app"> <div class="image"> <div class="overlay"> <p>Some overlay text</p> </div> <img src="https://placeimg.com/640/480/any" class="img-fluid"> ...