Angular JS form cloning feature

I'm facing a challenge in creating a dynamic form with multiple sections. At the end of the form, I want to include a "Add New Form" button which will duplicate the existing form below it, each with its own save button. What's the most effective approach to implement this using AngularJS? How can I use a single controller to handle all the forms and determine where the data should be submitted upon saving?

Appreciate any guidance on this issue.

Answer №1

If you want to display multiple forms in your application, you can define an array in the controller and use ng-repeat to render them:

Here is how you can achieve this:

<div ng-app="myApp" ng-controller="MyController">
    <div ng-repeat="form in forms">
        <hr/>
        <form name="myForm" ng-init="name = form.name">
            {{name}}
            <input name="myInput" type="text" ng-model="myInputValue"></input>
            <input type="button" value="Save" ng-click="saveForm(this)" ng-disabled="!myForm.$dirty"></input>
        </form>
    </div>
    <hr/>
    <input type="button" value="Create form" ng-click="createForm()"></input>
</div>

In the JavaScript part of your code:

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);            
    };
}]

You can check out the working example on http://jsfiddle.net/nfvjv0uv/2/.

Note that when using ng-repeat, a child scope is created for each iteration which we handle in the save method.

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

The information is not appearing in the dropdown menu

The select tag for chapters is not displaying the result from the query properly. Instead of showing in the select tag, the chapter names are being displayed as echo statements. <!doctype html> <html> <head> <meta charset="utf-8"> ...

Determine the precise boundaries of the React component

I am working with a basic ellipse element: <span style={{ width: /*someWith*/, height: /*someHeight*/, borderRadius: "50%" }}/> and, I am using getBoundingClientRect() to retrieve its bounds (displayed in blue). Everything see ...

Display or conceal fields depending on custom object specifications

I am attempting to centralize my show/hide functionality for fields in one object (like vm.foo) that contains key-value pairs. For example, I could add another pair like 1502: true to hide a field with the key 1502. Is there a way to pass variables from t ...

Ways to guarantee the protection of APIs that are accessible to both front-end applications and other servers

In the process of creating a website, I am faced with the challenge of enabling the front-end page to communicate with the server using AJAX for data retrieval and posting. The same APIs offered by the server are also utilized by private apps within the ...

What is the best way to activate ng-change only when the drag operation is completed in a directive?

Seeking a simple solution to trigger ng-change only when drag-end occurs. Previously achieved directly from HTML: <md-slider aria-label="{{ key }}" step="{{ value.step ? value.step : 1 }}" ng-model="filters.lastAppliedFilter.options[key].current" ng-c ...

Using Vue.js to eliminate duplicate values from a filtered array of objects

How can I eliminate duplicate data from a v-for loop in Vue.js? I have an array of clients and another array of categories. When filtering the categories based on clientIDs, I noticed that there are duplicates present. Please choose a client from the opti ...

Concealing the URL Once Links are Accessed

I have a Movie / TV Shows Streaming website and recently I've noticed visitors from other similar sites are coming to my site and copying my links. Is there a way to hide the links in the address bar to make it more difficult for them to access my con ...

The ngRoute feature seems to be malfunctioning and unable to switch views when an <a> tag is clicked

Just starting out with Angular JS and encountering an issue that has me stumped. Would really appreciate some help in resolving it. In my project, I have an index file connected to app.js which utilizes ngRoute. See the code snippet below for reference: ...

Having trouble with the JSFiddle dropdown button that is unresponsive to

I am currently in the process of developing a test drop-down menu. The open menu button functions correctly, however, the close button is unresponsive to clicking or hovering actions. Upon clicking the open menu button, it should make the other button visi ...

Passing parent props to child components in Vue.js - A comprehensive guide!

Trying to understand the process of passing a prop from parent to child components. If I include the prop attribute with the #id within the child component tag, like Image cid="488484-49544894-584854", it functions correctly. However, I am interested in u ...

What is the best way to restrict users from accessing more than 5 Bootstrap Tab-Panes at once?

Users are restricted to opening only a maximum of 5 tab panes, even if there are multiple tab buttons available. If the user tries to click on the 6th tab, an alert message will be displayed. function addTab(title, url){ var tabs=$(".tabs"), tab ...

Struggling to find a solution for changing the color of a select box when an option is chosen

Here's an example of the HTML I'm working with: <select onclick="colorchanger()"> <option name="white" value="0">--Select--</option> <option name="red" value="1">Work</option> <option name="green" value="2" ...

Capture a snapshot of a webpage that includes an embedded iframe

Currently, we have a nodeJS/angular 4 website that contains an iframe from a third party (powerBI Emebdded). Our goal is to develop a feature that allows the end user to capture a screenshot of the entire page, including the content within the iframe. We ...

How can I properly reset a timeout duration?

I'm currently working with a function that looks like this: function blabla(){ ... setTimeout(() => { //do some stuff }, 10000) } My question is, how can I reset the time of the timeout (10000) if the function was called and ...

Troubleshooting $on in Angular

I have a situation where I need to pass a value from the Main controller to the Child controller. These are the two controllers involved: .controller('mainController', ['$scope', '$rootScope', '$location', 'CI ...

Encoding a multidimensional associative array into JSON using PHP

Having used php's json_encode() function frequently in the past, I am puzzled by the current issue... Note: Error checking has been omitted for clarity. //PHP <?php session_start(); require 'global/query.php'; $sql = "SELECT sfl,statio ...

How can I add text to a textbox within a duplicated div using Javascript or Jquery?

I'm looking to add text to a cloned div's text box using jQuery. I have a div with a button and text box, and by cloning it, I want to dynamically insert text into the new div. $(document).ready(function () { $("#click").click(function () { ...

Inputting Information into a MySQL Database Using an HTML Form

Hey everyone! I have a simple web form that is supposed to input data into a MySQL database. I wrote some code to check if the connection to my database was working, and it seemed fine. However, when I submitted the form, no data was actually entered into ...

The Ajax PHP function only works on the initial call

The function below calls a PHP file that returns results in JSON format, which are assigned to JavaScript values. The PHP function has been thoroughly tested and works as expected. The results are stored in variables until the market variable is changed wi ...

Utilizing BackboneJs to Access and Fetch Data from an asmx Webservice

Could someone please help me with a code snippet to understand how to call asmx web services from a backbone collection? The provided example is very simple. Collection window["Persons"] = Backbone.Collection.extend({ model: Person, url: ...