What is the best way to generate an array containing multiple arrays, each filled with dynamic Divs?

I have the following code that displays a Div when the user clicks on the Add button. For example, if the user clicks the Add button 5 times, then 5 will be displayed with the same controls/inputs under default.

html

<div ng-repeat="st in stu">    
<div class="panel-body form-horizontal">
        <button ng-click="addStudent = true" class="btn btn-primary">
            Add new Student
        </button>

        <div class="form-group">
            <label class="col-lg-2 control-label required">Roll No.</label>
            <div class="col-lg-4">
                <input type="text" id="rollNo" name="runNumber" class="form-control" data-ng-model="RollNumber" ng-required="true" maxlength="100" />
            </div>
        </div>

        <div class="form-group">
            <label class="col-lg-2 control-label">Student Name</label>
            <div class="col-lg-4">
                <input type="text" name="studentName" class="form-control" data-ng-model="StudentName" maxlength="500" />
            </div>
        </div>

        <div class="form-group">
            <label class="col-lg-2 control-label">Class Name</label>
            <div class="col-lg-4">
                <input type="text" name="Class" class="form-control" data-ng-model="ClassName" maxlength="500" />
            </div>
        </div>
    </div>
</div>

Controller

    $scope.addStudent = function () {
        var item = $scope.students.length + 1;
        $scope.stu.students(item);
    };

Everything is working fine up to this point.

However, I am trying to further implement that when the user enters information in, let's say, 3 DIVs and clicks on the Save button, the information from each DIV should be wrapped in a different array...

For example:

Students[[{Roll No:1, StudentName: 'Test1', Class Name: 'test1'}],[{Roll No:2, StudentName: 'Test2', Class Name: 'test2'}],[{Roll No:3, StudentName: 'Test3', Class Name: 'test3'}]]

I am unsure how I can implement that? Any suggestions?

Answer №1

<div class="panel-body form-horizontal">
    <button ng-click="addStudent()" class="btn btn-primary">
        Add new Student
    </button>

<div ng-repeat="user in users">
    <div class="form-group">
        <label class="col-lg-2 control-label required">Roll No.</label>
        <div class="col-lg-4">
            <input type="text" id="rollNo" name="runNumber" class="form-control" data-ng-model="user.Roll_No" ng-required="true" maxlength="100" />
        </div>
    </div>

    <div class="form-group">
        <label class="col-lg-2 control-label">Student Name</label>
        <div class="col-lg-4">
            <input type="text" name="studentName" class="form-control" data-ng-model="user.StudentName" maxlength="500" />
       </div>
    </div>

    <div class="form-group">
        <label class="col-lg-2 control-label">Class Name</label>
        <div class="col-lg-4">
            <input type="text" name="Class" class="form-control" data-ng-model="user.ClassName" maxlength="500" />
        </div>
    </div>
</div>
</div>

Controller:

$scope.userRecord = [
                {Roll_No:1, StudentName: 'Test1', ClassName: 'test1'},
                {Roll_No:2, StudentName: 'Test2', ClassName: 'test2'},
                {Roll_No:3, StudentName: 'Test3', ClassName: 'test3'}
               ];

$scope.count = 0;

$scope.addStudent = function () {
    $scope.count +=1;
    $scope.users = [];

    for(var j=1; j <= $scope.count; j++){
        angular.forEach($scope.userRecord,function(user){
                if(user.Roll_No === j){
                        $scope.users.push(user);
                }
        });
    }
}

Answer №2

school = {
        "room1" : {
                 "Roll no" : 1,
                 "StudentName" : 'John',
                 "Class Name" : 'Math' 
                },
        "room2" :{
                 "Roll no" : 2,
                 "StudentName" : 'Jane',
                 "Class Name" : 'Science' 
                 }
        and so forth...
        };

you can then retrieve the data like this

console.log(school.room1);

when a button is clicked, simply add another object (or room) to the array using a counter variable to track the increment

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

What potential issues arise from utilizing useRef alongside useSelector?

Although I have the capability to access the store by using thunks and/or global stores, I avoid binding my component to the Redux store. This is because the component will be utilized with various stores both inside and outside of the project. The compone ...

The issue with the Sails.js application is that it fails to update files from assets after

Currently, I am working on a Sails.JS application with Angular.JS as its front-end framework. All the angular files are stored in /assets/linker and they are correctly injected upon start. However, I have encountered an issue where any changes made to the ...

Verify whether the div contains a specific class before triggering the animation

I'm attempting to create an animation following a user interaction with the Owl Carousel drag feature. The issue I'm encountering is that the code referencing $(this) does not recognize the .nav-item element with the .active class. Any insights ...

Is it possible to nest ng-repeat and access $first and $last properties simultaneously

Below is the form that I am currently working with, <tbody ng-repeat="attGroup in attributesGroups"> <tr> <td class="vcenter text-right"> &nbsp;&nbsp;<a href="javascript:" ng-click="!$last && up ...

What is the process for setting data to the value attribute in an input tag, retrieved from a firebase database?

I utilized the following code snippet to retrieve data from Firebase database and store it in the Name variable. var userId = localStorage.getItem('keyName'); var dbRefName = firebase.database().ref() .child(& ...

Updating JSON data in real time using JavaScript by manipulating MySQL database entries

My database has a mysql structure consisting of the columns ID, NAME, and TYPE. The data is then converted into a JSON format as shown below: [ {id: "1", name: "Snatch", type: "crime"}, {id: "2", name: "Witches of Eastwick", type: "comedy"}, { ...

Is there a way to determine the dimensions of the DOCUMENT using Javascript instead of the VIEWPORT?

To ensure clarity, let me explain the distinctions between document, window, and viewport.... WINDOW refers to the entire browser window, including all navigation bars, etc.... VIEWPORT is the section of the window used to view the current XHTML/HTML/Fla ...

React: What is the best way to dynamically render images by iterating through a list?

Currently, I am attempting to iterate through an array of objects. Each object within the staff array in my JSON contains an imgUrl: { "home": { ... "staff": [ { ... "imgUrl": "../Images/Jon ...

Filling in a text field with the text content (rather than the value) from a dropdown menu

Presently, I have the select box with the id "title" populating a text field with the id "costcenter". The current code works perfectly fine when using the VALUE of the select box to trigger the population of the cost center field. However, my requirement ...

When setting up columns in a MUI DataGrid, it's important to remember that each field must have a unique name to avoid any conflicts. Having

I am currently working on a DataGrid project where I aim to display the values of ready_by and name. Here is an image for reference: https://i.stack.imgur.com/3qZGa.png In my code configuration, the setup looks like this: (specifically focusing on the la ...

Issue with XMLHttpRequest.send() not working in Google Chrome when using POST requests

I'm currently developing an application where users can send files using a form through a POST request. As the file uploads, the application makes multiple GET requests to gather information about the upload progress. Interestingly, this functionalit ...

Top tips for handling HTML data in JSON format

I'm looking to fetch HTML content via JSON and I'm wondering if my current method is the most efficient... Here's a sample of what I'm doing: jsonRequest = [ { "id": "123", "template": '<div class=\"container\"&g ...

Setting a CSS Variable with the Help of jQuery

I need help with changing the background color of a specific .div element when it is clicked on. I want the color to be a variable that can be changed by the user, and this change should occur when the document is ready. Currently, I am using a CSS variab ...

Eslint is actively monitoring files specified in the eslintignore to ensure they meet the set

I am currently working on a TypeScript project that is bundled by Webpack. I want to integrate Eslint into the project, but I have encountered an issue where Eslint watches compiled files even if they are listed in the .eslintignore file. .eslintignore: . ...

Leveraging promises to make Ajax calls without repeating code

Would it be possible to create an ajax function without duplicating it? Passing different parameters, which are locations to various files. Then utilizing the promise to combine them into a single object, possibly incorporating the spread operator. Is th ...

What is the process for sending text messages in a local dialect using node.js?

Having an issue with sending bulk SMS using the textlocal.in API. Whenever I try to type a message in a regional language, it displays an error: {"errors":[{"code":204,"message":"Invalid message content"}],"status":"failure"} Is there a workaround for se ...

What is the best way to animate the preprending of a div in an AJAX response?

Here is the code I am currently working with: $.ajax({ type: 'POST', url: 'load_more.php', data: {val:myval}, success: function (data) { $("#load_current").prepend(data); ...

"What is the best way to use JavaScript to dynamically modify the hover color of a button

I am looking to customize the hover color of all buttons on my website to align with the overall theme. The challenge is that I need the hover color to vary based on the page it originates from. I have successfully identified the referring page, but I am s ...

Tips for refreshing the default style of Material UI select

I'm having trouble customizing the default background color of the first menuItem in the select component. The class I need is not visible when inspecting the element, as the background color disappears upon inspection. Steps to reproduce: 1. Click ...

Experiencing difficulties with JWT implementation and seeking to transmit the JWT token to additional APIs

I am currently working on implementing JWT authentication in node js/express js: Below is the sample code I have written for this purpose: const jwt = require('jsonwebtoken'); const secretKey = crypto.randomBytes(64).toString('hex'); c ...