Creating dynamic forms using AngularJS and the ng-repeat directive

i am working with AngularJS dynamic forms . According to my userid value i generated multiple form field with same model name using ng-repeat. i am not able to get this input model values due to this ng-repeat. in this example i am using static userid data.

<div ng-app="myApp">
<div ng-controller="myCtrl">
    <form role="form" name='userForm' novalidate>
        <div class="container">
            <div class="row" ng-repeat="myid in userid">
                <div class="form-group">
                    <div class="col-md-3">
                        <label>ID</label>

Let's shift our focus to the JavaScript portion where the functionality is controlled and manipulated:

<pre><code>var myApp = angular.module('myApp', []);
 myApp.controller('myCtrl', function($scope) {
   $scope.userid = [1, 2, 3];
   $sope.adduser = function() {

}
});
As I venture towards sending an array of objects to the server, a concern arises regarding handling dynamic userids with an excess of 100 data points. How can I extract each field's model value comprehensively? Furthermore, what approach should be adopted to convert these model data entries into an array of objects resembling the sampleServerData structure showcased below?

i am expecting my final output data like this

var sampleServerData = [{
        "userid": 1,
        "manualcomment": "mycmt1",
        "gender": "male"
    }, {
        "userid": 2,
        "manualcomment": "mycmt2",
        "gender": "male"
    }, {
        "userid": 3,
        "manualcomment": "mycmt3",
        "gender": "female"
    }]

Answer №1

To enhance your code, consider changing the id of your textarea to a class, or introduce a textarea id within your user object (further details below).

If your ids are stored in an array, create an array of objects based on your ids array.

var ids = [1, 2, 3];
var users = ids.map(function(id) {
   return {id: id, comment: "", gender: ""};
})

For a helpful solution, I have prepared a jsbin for you. Make sure to click the run with js button as it may not run automatically when loaded.

HTML

<div ng-app="myApp">
<div ng-controller="myCtrl">
    <form role="form" name='userForm' novalidate>
        <div class="container">
            <div class="row" ng-repeat="user in users">
                <div class="form-group">
                    <div class="col-md-3">
                        <label>ID</label>
                        <input ng-model="user.id" id="user.id" name="user.id" placeholder="Enter bugid" type="text" required readonly disabled>
                    </div>
                    <div class="col-md-3">
                        <label>Comments</label>
                        <textarea ng-model="user.comment" id="textarea1" rows="1" required></textarea>
                    </div>

                    <div class="col-md-3 ">
                        <label>Gender</label>

                        <select ng-model="user.gender" name="select2" required>
                            <option value="male">Male</option>
                            <option value="female">Female</option>
                        </select>
                    </div>
                </div>

            </div>
        </div>
        <div class="buttonContainer text-center btn-container">
            <br>
            <button ng-disabled="userForm.$invalid" type="button" id="adduser" ng-click="adduser()">Add user</button>
            <button type="button" class="btn button--default btn--small pull-center">Close</button>
        </div>
    </form>
 </div>

JS

    var myApp = angular.module('myApp', []);
     myApp.controller('myCtrl', function($scope) {
      $scope.ids = [1, 2, 3];
   
      $scope.users = $scope.ids.map(function(id) {
        return {id: id, comment: "", gender: ""};
      });

      $scope.adduser = function() {
        var data = $scope.users.map(function(user) {
          return {
           "userid": user.id,
           "manualcomment": user.comment,
           "gender": user.gender
          }
      });
     
      console.log("data", data)
  }
});

Answer №2

To utilize ng-repeat in your HTML file, follow this structure:

<div ng-app="myApp">
    <div ng-controller="myCtrl">
        <form role="form" name='userForm' novalidate>
            <div class="container">
                <div class="row" ng-repeat="myid in userId">
                    <div class="form-group">
                        <div class="col-md-3">
                            <label>ID</label>
                            <input ng-model="userId[$index].id" id="myid"name="myid" placeholder="Enter bugid" type="text" required readonly disabled>
                        </div>
                        <div class="col-md-3">
                            <label>Comments</label>
                            <textarea ng-model="userId[$index].manualcomment" id="textarea1" rows="1" required></textarea>
                        </div>

                        <div class="col-md-3 ">
                            <label>Gender</label>

                            <select ng-model="userId[$index].gender" name="select2" required>
                                <option value="male">Male</option>
                                <option value="female">Female</option>

                            </select>
                        </div>
                    </div>

                </div>
            </div>
            <div class="buttonContainer text-center btn-container">
                <br>
                <button ng-disabled="userForm.$invalid" type="button" id="adduser" ng-click="addusers()">Add user</button>
                <button type="button" class="btn button--default btn--small pull-center">Close</button>
            </div>
        </form>
    </div>

Next, create the controller function as follows.

var myApp = angular.module('myApp', []);
 myApp.controller('myCtrl', function($scope) {
   $scope.userId = [1,2,3,4,5] // or new Array(3);

   $sope.adduser = function() {
     var serverData = $scope.userId;
   }
});

Answer №3

To utilize track by $index in ng-repeat and correlate the index with models:

<div class="row" ng-repeat="myid in userid track by $index">

<div class="form-group">
                    <div class="col-md-3">
                        <label>ID</label>
                        <input ng-model="userId[$index].id" id="myid"name="myid" placeholder="Enter bugid" type="text" required readonly disabled>
                    </div>
                    <div class="col-md-3">
                        <label>Comments</label>
                        <textarea ng-model="userId[$index].manualcomment" id="textarea1" rows="1" required></textarea>
                    </div>

                    <div class="col-md-3 ">
                        <label>Gender</label>

                        <select ng-model="userId[$index].gender" name="select2" required>
                            <option value="male">Male</option>
                            <option value="female">Female</option>

                        </select>
                    </div>

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

Transitioning images smoothly and responsively with jQuery, creating a beautiful

Hey there! I'm looking for some help with transforming this jQuery effect. Instead of having fixed sized images, I want to set the size in percentage (width:100%; height:auto) so they can be responsive. Any creative ideas or suggestions? <scri ...

Tips for creating a row template with pinned content

When setting pinning and rowTemplate together, the rowTemplate repeats 3 times in a single row. I suspect it is related to the pinning column, but I am unsure how to rectify it. Here's the link to the Plunker showcasing the issue: http://plnkr.co/ed ...

Is there a way to remove a dynamically rendered component from a list?

Whenever I click a button, the same component is dynamically rendered on top of the list. But now, I need to implement a feature where users can delete any component from the list by clicking a cancel button associated with each component. Here's my ...

Jest does not support util.promisify(setTimeout) functionality

While I understand there may be similar questions on SO, I believe mine is unique and hasn't been addressed in the current answers. I'm currently experimenting with testing a REST API in Express.JS. Below, you'll find a basic working exampl ...

CSS animations for loading page content

Currently, I am incorporating animations into my project using HTML5 and CSS3, and the progress has been smooth. I have been able to achieve effects such as: #someDivId { position: absolute; background:rgba(255,0,0,0.75); transition: all 0.7s ...

When utilizing jQuery to add a <li> element, it suddenly vanishes

? http://jsfiddle.net/AGinther/Ysq4a/ I'm encountering an issue where, upon submitting input, a list item should be created with the content from the text field. Strangely, it briefly appears on my website but not on the fiddle, and no text is appen ...

Steps to verify if a value is an integer:

Lately, I've been working on a "spinner" that increments and decrements a number by 1 each time. However, I'm struggling to add validation to the program so that it only accepts integers (no decimals). I've tried looking into NaN and parseVa ...

The default skin of video.js is disrupted by a 16:8 ratio

Incorporating videojs into my react application has presented a challenge. I have enclosed the video player in a div set to a 16:8 ratio, but unfortunately the default skin does not display properly. On the other hand, when I implement code that includes t ...

Adding additional rows to an Array Object in JavaScript based on a certain condition

I am faced with a scenario where I have an array object structured as follows [ { id: 123, startdate: '2022-06-05', enddate: '2023-04-05' },{ id: 123, startdate: '2021-06-05', enddate: '2021-04-05' } ] The task at h ...

Accessing results from geocoder.geocode is restricted to local variables only

I need to extract longitude and latitude coordinates from google.maps.GeocodeResults in order to store them in an external Array<any>. Currently, I am able to display results[0], but encounter an OVER_QUERY_LIMIT error when attempting to add it to t ...

Fixing the error message stating 'Argument of type '{}' is not assignable to parameter of type 'any[]'. [ng] Property 'length' is missing in type '{}'. Here are steps to resolve this issue:

Currently, I am in the process of developing an Ionic Inventory Management application that incorporates a Barcode Scanner and SQLite database by following this tutorial: Upon adding the following code snippet: async createTables(){ try { awa ...

methods for efficient set computations

I have a collection of sets in the format (a,b) which are as follows: (2,4) (1,3) (4,5) (1,2) If I am given a pair like <2,1>, I want to identify all sets in the collection where 2 or 1 is the first element. In this case, it would be (2,4), (1,3), ...

Trouble with component not refreshing upon store modification in Vuex

Summary: If you prefer, I have a video detailing my issue: https://youtu.be/Qf9Q4zIaox8 Concern with Navbar Component Not Updating on Store Change. The issue I'm facing involves the Navbar component not updating when there is a change in the store. ...

JavaScript function is not identifiable

I am currently developing a tic-tac-toe game with 9 buttons that will display either an X or O image depending on the boolean value of the variable isX. The main container for these buttons is a div element with the id 'stage' and each button ha ...

In the event that the hash consists of just one string, disregard any additional conditional statements

Currently, I am in the process of updating one of my coding playgrounds and facing some issues. If the user has only the "result" string in the hash like this... testhash.html#d81441bc3488494beef1ff548bbff6c2?result I want to display only the result ( ...

Enhancing Dataset Quality: Incorporating Failed Results with Apify

We have implemented the Apify Web Scraper actor to execute a URL validation task that retrieves the input URL, the title of the page, and the HTTP response status code. Our testing includes 5 URLs - 4 valid ones and 1 non-existent URL. The successful resul ...

Error encountered when attempting to insert data into database due to incompatible data types

I am experiencing an issue with Vue multiselect. I am trying to save the id of selected options in a database, but it seems that I am encountering an error related to Array to string conversion. I have declared both site_id and administrator in fillables. ...

Embed Text inside an HTML Canvas

As someone who is relatively new to working with html canvas, I am having a bit of trouble when it comes to containing text within the canvas area. Specifically, I am pulling text from a textarea and displaying it on the canvas, but it seems to stay as one ...

The word-break CSS property is ineffective in this situation

I've been experimenting with the word-break css property, but I just can't seem to get it to work even when using a simple example. Here's my code: React: render() { return ( <h5 className="word-break">A very very long line.... ...

I'm confused by the function: "sort((a: Article, b: Article) => b.votes - a.votes);"

I'm having trouble grasping the concept of the return statement in sortedArticles(). Can anyone provide me with a resource or explain how this sorting function works? sortedArticles(): Article[] { return this.articles.sort((a: Article, b: Article ...