AngularJS: Batch processing for saving multiple students simultaneously

I have been working on saving information about students, and I've written the code below. However, I'm unsure how to proceed from here. Any additional information or resources related to this topic would be greatly appreciated.

<div ng-controller="MainCtrl">
    <fieldset data-ng-repeat="student in students"> 
        <input type="text" ng-model="student.class" name="" placeholder="Class Name ">                
        <input type="text" ng-model="student.firstname" name="" placeholder="First Name ">
        <input type="text" ng-model="student.lastname" name="" placeholder="Last Name ">
        <button class="btn btn-danger" ng-show="$last" ng-click="removeStudent()">-</button>
    </fieldset>

    <button class="btn btn-primary" ng-click="addNewStudent()">New Student</button>
    <button class="btn btn-primary" ng-click="save()">Save</button>
    <button class="btn btn-warning" ng-click="cancel()">Cancel</button>                
 </div> 

Below is the controller:

app.controller('MainCtrl', function($scope, $modalInstance, $students) {
    $scope.students = [];

    $scope.addNewStudent = function() {
        $scope.students.push({
            classname: "",
            firstname: "",
            lastname: ""
        });
    };
    $scope.removeStudent = function() {
        var lastItem = $scope.students.length - 1;
        $scope.students.splice(lastItem);
    };

    $scope.save = function() {
        $modalInstance.close($scope.students);
    };

    $scope.delete = function() {
        $scope.students['deleted'] = 1;
        $modalInstance.close($scope.students);
    };

    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };
});

While I am able to input student information in the view, clicking the save button only saves the details of the first student.

Modal Instance:

$scope.openStudent = function (student) {

var modalInstance = $modal.open({
    templateUrl: 'modalStudent.html',
    controller: 'mainCTRL',
    windowClass:'app-modal-window',
    resolve: {
        students: function () {
            var students= {};

            if (student !== undefined){
                students['classname'] = student.classname; 
                students['firstname'] = student.firstname ; 
                students['lastname'] = student.lastname; 
                students['nachname'] = student.nachname; 

            }
            console.log("studinfo",students);
            return students;
        }
    }
});

modalInstance.result.then(function (students) {

    if (students.deleted  === undefined || students.deleted == 0) { 
        oStudent = { classname: students.classname, 
                    firstname: students.firstname, 
                    lastname: students.lastname,
                    delete_time:"0000-00-00 00:00:00"
                    };

        saveStudent( $indexedDB,Student).then( function(id) {
            $scope.buildMenu();
        });
    } else {
         oStudent = { id: students.id,
                    delete_time:new Date().toISOString()
                    };
        deleteStudent( $indexedDB, $scope, students.id).then( function(id) {
            saveStudent( $indexedDB, Student, $scope.selectedUser.id ).then( function(id) {
            $scope.buildMenu();
        });
        });
    }
}, function () {
    //console.log('Modal Student dismissed at: ' + new Date());
});
}

Answer №1

If you are dealing with a modal that involves passing existing student objects, your controller code needs to be adjusted as follows:

It is recommended to use separate views for adding and editing students in order to prevent code clutter. When adding a student, the data will be an array of objects, whereas when editing, it will be a single object. This means that ng-repeat cannot be used in both cases.

app.controller('MainCtrl', function($scope, $modalInstance, students) {

    // The 'students' variable contains information about the student being edited, so your code should handle this scenario
    if(students.classname !== undefined){
         $scope.students = students;   
    }else{
         $scope.students = [];
    }

// Instead of re-initializing every time the modal is opened, retain the value passed via 'students'

    $scope.addNewStudent = function() {
        $scope.students.push({
            classname: "",
            firstname: "",
            lastname: ""
        });
    };
    $scope.removeStudent = function() {
        var lastItem = $scope.students.length - 1;
        $scope.students.splice(lastItem);
    };

     $scope.save = function() {
        $modalInstance.close($scope.students);
         // Ensure to save this data when the modal closes, using the returned students variable
    };

    $scope.delete = function() {
        $scope.info['deleted'] = 1;
        $modalInstance.close($scope.students);
    };

    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };
});

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 is the process for deleting headers in a $http.get call and simultaneously including "application/json" and "text/plain" under the "Accept" header?

I'm relatively new to angularjs and I'm currently working on implementing some new features to an existing Angular JS application. The current API calls are quite intricate so I decided to make a direct call. Below is the code snippet for my new ...

perform an action if any division element is void of content

Currently, I have a statement that checks if any of the Divs with the ID #Drop are empty. If one is found to be empty, an alert is shown. However, there seems to be an issue where the statement stops working when any div contains content. What I am trying ...

Are programmatic clicks distinguishable from manual clicks in JQuery?

Currently, I am in the process of creating selectable and draggable elements for a table. You can test the functionality by following this JsFiddle link (please try vertically selecting). Initially, the selection works well but upon trying to select for th ...

What is the best location in Backbone.js to store code unrelated to the view, such as ads and analytics?

In my development of a backbone.js application, I have come to understand the role of each backbone "class" as follows: Model: This represents the data object, where the outcome of an API call is stored. Collection: An organized group of models, for exam ...

What is the best way to establish a client.js file for socket.io in Node.js?

I am looking to separate the client script from the index.html file in the chat application example found at https://socket.io/get-started/chat/. Currently, I am facing an issue where the message "a user connected" is not appearing when I refresh the webpa ...

A guide to utilizing Forwarding References in react-router-dom

I have a good grasp on Forwarding Refs and react-router-dom, but I'm struggling with the implementation in this particular scenario. The issue lies in trying to correctly use a function in a child component that sets null in a useState hook. I want th ...

Clicking through the button inside Vuetify's text-field append slot

While working on creating Vuetify's v-text-field with a slot named append containing a button, everything seems to be functioning correctly except for the fact that when I click the button, it goes through and focuses on the text field. On mobile devi ...

Add a plugin to the website after the DOM has finished loading

Here is a code snippet that utilizes a jQuery plugin to apply scrollbars to a DOM element: <script type="text/javascript"> $(document).ready(function () { $(".pp-meta-content").customScrollbar(); }); </script> This code works ...

Tips for adding a "Select All" feature to a dropdown list?

Currently, I have a dropdown list with a filter for IN and OUT values. The functionality is working as expected: <select class="form-select" style="max-width: 100px" [ngModel]="selectedBrand" (ngModelChange)="onChangeT ...

The function is receiving an empty array of objects

This code is for an Ionic app written in typescript: let fileNames: any[] = []; fileNames = this.getFileNames("wildlife"); console.log("file names:", fileNames); this.displayFiles(fileNames); The output shows a strange result, as even though there ar ...

Is it possible to make this functionality Angular-friendly?

I am in the process of transforming a Bootstrap + jQuery theme into Angular JS, and I am encountering some challenges along the way. One issue is related to the functionality provided in the JS file of the theme: /* Sidebar Navigation functionality */ var ...

Ways to extract a number that comes after a specific word in a URL

I have a URL and need to extract a specific value from it by removing a certain step. I am looking for a regex solution to accomplish this task For example, if I have the window.location.href, the URL might look like this: https://mypage/route/step-1/mor ...

Solving Cross-Origin Resource Sharing problem in an Express JS application

I have encountered a CORS error while using this code, despite having applied the necessary cross-origin headers. I am seeking guidance on how to resolve this issue. var express = require('express'); var bodyParser = require('body-parser&ap ...

Is it permissible for me to incorporate a package from the dependencies listed in the package-lock.json file into my

I'm looking to incorporate date-fns into my project. I currently have react-datepicker, which also uses date-fns. Can I simply utilize date-fns from react-datepicker, or do I need to install it separately in my project? ...

What is the best way to showcase a singular item from response.data?

Below is the controller I have set up to display details of a single book from my collection of json records .controller('BookDetailsController', ['$scope','$http','$stateParams',function($scope,$http,$stateParams){ ...

How to choose the final option in a multiselect using AngularJS and md-options

Below is the code snippet in question: <md-select multiple ng-model="filtered" placeholder="Select a team member" ng-show="onTeam"> <md-option ng-value="opt.value" ng-repeat="opt in allowedStatuses" selected="{{ opt.value === opt.last ? &a ...

What is the process for setting a specific version of Node for a project on my local machine?

I am currently facing an issue with setting up Node across multiple developers' machines for a project. The challenge lies in the fact that not all team members are experienced in Node or JavaScript, and we need to ensure that everyone has the correct ...

JavaScript tag filtering system: Display only the div elements that contain all the specified classes in an array; otherwise, hide them

Can you provide some guidance on accomplishing this task? I am looking to toggle the visibility of a div based on its classes and an array. If the array contains the term something, then only divs with the class something will be displayed. If the array ...

Is a webpage's sluggishness in Internet Explorer due to its lengthy page structure causing issues while loading quickly on other browsers?

My application has a page that is particularly long, around 8Mb of source HTML mainly comprised of tables. I am aware that this indicates poor architecture, but unfortunately, I am unable to make immediate changes due to certain constraints. In most brows ...

Displaying Well-Formatted XML in Angular2 Using Typescript

After receiving this XML string from the server: <find-item-command xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" find-method="Criteria" item-class="com" only-id="false" xsi:schemaLocation=""> <criteria> <criterion> <descripto ...