Encountering a problem with CRUD operations when attempting to edit and save data from a table using

When attempting to edit the information by clicking the radio button, the details are displayed in the appropriate boxes but the existing data in the table is deleted. My goal is to utilize a single array/scope variable for editing, displaying, and deleting without using loops for edit/delete operations. Although I made some changes, it still doesn't work properly. Below is my HTML index.html:

<div ng-controller="employeeController">
    <header><h1>Employee Details</h1></header>

    <form name="myForm" novalidate>
        <table id="myTable" cellspacing="0" cellpadding="4">
            <tr>
                <td><label> Employee Id </Label></td>
                <td><input type="text" name="eid" data-ng-model="employees.EmployeeId" data-ng-required="true" ng-disabled="newEmployees"/></td>
            </tr>
            <tr>
                <td><label> FirstName </Label></td>
                <td><input type="text" name="fname" data-ng-model="employees.FirstName" data-ng-required="true"/></td>
            </tr>
            <tr>
                <td><label> LastName </Label></td>
                <td><input type="text" name="lname" data-ng-model="employees.LastName" data-ng-required="true"/></td>
            </tr>
            <tr>
                <td><label> Gender </Label></td>
                <td>
                    <input type="radio" name="gender" data-ng-change="employees.Gender" value ="Male" data-ng-model="employees.Gender"/> Male
                    <input type="radio" name="gender" data-ng-change="employees.Gender" value ="Female" data-ng-model="employees.Gender"/>Female
                </td>
            </tr>
            <tr>
                <td><label> Email </Label></td>
                <td><input type="text" name="email" data-ng-model="employees.Email" data-ng-required="true"/></td>
            </tr>
            <tr>
                <td><label> Account </Label></td>
                <td><input type="text" name="account" data-ng-model="employees.Account" data-ng-required="true"/></td>
            </tr>
            <tr>
                <td><input type="hidden" data-ng-model="employees.EmployeeId"></td>
            </tr>
        </table>
        <button name="btnSave" data-ng-click="saveEmployeeRecord(employees)" class="userbutton">Save</button>
        <button name="btnReset" data-ng-click="resetEmployeeRecord()" class="userbutton">Reset</button>
    </form> 

    <table border="2" cellspacing="0" cellpadding="4">
        <tr style="color: blue">
            <th style="width:100px">Employee Id</th>
            <th style="width:150px">FirstName</th>
            <th style="width:150px">LastName</th>
            <th style="width:90px">Gender</th>
            <th style="width:150px">Email</th>
            <th style="width:60px">Account</th>
            <th>Action</th>
        </tr>
       <tr style="color:green" data-ng-repeat="emp in employees">
           <td>{{emp.EmployeeId}}</td>
           <td>{{emp.FirstName}}</td>
           <td>{{emp.LastName}}</td>
           <td>{{emp.Gender}}</td>
           <td>{{emp.Email}}</td>
           <td>{{emp.Account}}</td>
           <td>
               <input type="radio" name="process" data-ng-click="editEmployee(emp, employees.indexOf(emp))"> Edit
               <input type="radio" name="process" data-ng-click="DeleteEmployee(employees.indexOf(emp))"> Delete
           </td>
       </tr>
   </table>
</div>

Javascript app.js

var employeeApp = angular.module("myApp",[]);

employeeApp.controller("employeeController", function($rootScope, $scope, $http) {

            $http.get('data/employees.json').success(function(data) {

                $rootScope.employees = data;
            }); 

            var empId = 12342;
            $rootScope.saveEmployeeRecord = function(emp) {
                if($rootScope.employees.EmployeeId == null) {
                    $rootScope.employees.EmployeeId = empId++;
                    $rootScope.employees.push(emp);
                }
                else {
                    for(i in $rootScope.employees) {
                        if($rootScope.employees[i].EmployeeId == emp.EmployeeId) { 
                            $rootScope.employees[i]= emp;
                        }
                    }
                }

                //$rootScope.employees = {};
            }

            $rootScope.resetEmployeeRecord = function() {
                angular.copy({}, $rootScope.employees);
            }

            $rootScope.editEmployee = function(emp, indx) {

                    //$rootScope.emp = $rootScope.employees;
                    if($rootScope.employees[indx].EmployeeId == emp.EmployeeId) { 
                        $rootScope.employees = angular.copy($rootScope.employees[indx]);
                    }


            }

            $rootScope.DeleteEmployee = function(idx) {

                var result = confirm("Are you sure want to delete?");
                if (result) {
                    $rootScope.employees.splice(idx,1);
                    return true;
                }
                else {
                     return false;
                }

                //for(i in $rootScope.employees) {
                    //if($rootScope.employees[i].EmployeeId == idx) { 

                        //$rootScope.employees = {};
                    //}
                //}
            }

});

employees.json file:

[
            {
                "EmployeeId": "61234",
                "LastName": "Anderson",
                "FirstName": "James",
                "Gender": "Male",
                "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="315b505c54426e505f555443425e5f71585f575e4248421f525e5c">[email protected]</a>",
                "Account": "Boeing"
            },
            {
                "EmployeeId": "512458",
                "LastName": "Cambell",
                "FirstName": "Mike",
                "Gender": "Male",
                "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e1317151b501d1f131c1b12123e171018110d070d501d1113">[email protected]</a>",
                "Account": "Boeing"
            },
            {
                "EmployeeId": "712785",
                "LastName": "Swachengar",
                "FirstName": "Andrew",
                "Gender": "Male",
                "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9a8a7adbbacbee7babea8aaa1aca7aea8bb89a0a7afa6bab0bae7aaa6a4">[email protected]</a>",
                "Account": "Cisco"
            },
            {
                "EmployeeId": "712734",
                "LastName": "Anderson",
                "FirstName": "James",
                "Gender": "Male",
                "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c1aba0aca4b2efa0afa5a4b3b2aeaf81a8afa7aeb2b8b2efa2aeac">[email protected]</a>",
                "Account": "Apple"
            },
            {
                "EmployeeId": "61245",
                "LastName": "Green",
                "FirstName": "Rachael",
                "Gender": "Female",
                "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aad8cbc9c2cbcfc6f5cdd8cfcfc4eac3c4ccc5d9d3d984c9c5c7">[email protected]</a>",
                "Account": "Boeing"
            },
            {
                "EmployeeId": "61347",
                "LastName": "Brown",
                "FirstName": "Jackualine",
                "Gender": "Female",
                "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa909b99918f9b9693949fa59888958d94ba93949c95898389d4999597">[email protected]</a>",
                "Account": "Boeing"
            }
] 

Answer №1

To ensure the selected item is properly assigned to a model for association in your edit/save form, you must update the original data with the new data when the "save" button is clicked. Consider this approach:

        $scope.saveEmployee = function() {
            for(key in $scope.selectedEmployee){
             $scope.selectedEmployee[key] = $scope.selectedEmployeeCopy[key];
            }
        }

        $scope.resetEmployee = function() {
            $scope.selectedEmployeeCopy = null;
        }


        $scope.editSelectedEmployee = function(employee) {
            $scope.selectedEmployee = employee;
            $scope.selectedEmployeeCopy = angular.copy($scope.selectedEmployee);
        }

In this example, I duplicate the original employee object before making any updates. After saving, the duplicated version replaces the original. If changes are discarded, the duplicate is simply disregarded. Check out a live demo demonstrating this concept.

Edit: Following feedback, refined the save and delete methods that weren't functioning correctly. JSFiddle has also been updated. Edit2: Replaced for loops with indexing array elements for efficiency

    $scope.saveEmployee = function() {
            $scope.employees.splice($scope.selectedIndex, 1, $scope.selectedEmployeeCopy);
        }

        $scope.resetEmployee = function() {
            $scope.selectedEmployeeCopy = null;
            $scope.selectedIndex = null;
        }

        $scope.editSelectedEmployee = function(emp, index) {
            $scope.selectedIndex = index;
            $scope.selectedEmployee = emp;
            $scope.selectedEmployeeCopy = angular.copy($scope.selectedEmployee);
        }

        $scope.deleteEmployee = function(emp, index) {

            var confirmation = confirm("Are you sure you want to delete?");
            if (confirmation) {                    
                $scope.employees.splice(index, 1);
                $scope.selectedEmployeeCopy = null;
                $scope.selectedIndex = null;
                return true;
            }
            else {
                 return false;
            }
        }

Answer №2

If you want to include an id along with your index in a radio button, you can do so like this:

<button class="btn btn-default" ng-click="editBook(add.id, $index);" type="submit">Edit</button>

Here is an example of how it can be implemented in the controller:

$scope.editBook = function(id, index) {
   $scope.show1=false;
   $scope.show=true;
   $http.get(appurl + 'user/adds/' + id + '.json')
        .success(function(data, status, headers, config) {
            $scope.user= data; 
            angular.copy($scope.user, $scope.copy);
        });
};

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

Experiencing difficulties when conducting a Karma test on an Angular service

My examination is: 'use strict'; (function() { describe('Service: Assessment', function () { var $httpBackend; // load the service's module beforeEach(module('mean')); var AssessService; beforeEac ...

Emphasizes the P tag by incorporating forward and backward navigation options

My goal is to enable users to navigate up and down a list by pressing the up and down arrow keys. For example, if "roma" is currently highlighted, I want it to change to "milan" when the user presses the down arrow key. Here is the HTML code I am working w ...

Conceal descendant of list item and reveal upon clicking

In my responsive side menu, there is a submenu structured like this: .navbar ul li ul I would like the child menus to be hidden and only shown when the parent menu is clicked. Although I attempted to achieve this with the following code, it was unsucces ...

What sets server-side development apart from API creation?

As I dive into the world of web development, I find myself facing some confusion in my course material. The instructor has introduced concepts like promise objects and fetch, followed by axios, and now we're delving into the "express" package for buil ...

Is it possible to deactivate a form control in AngularJS using a variable?

I am facing a situation where I have three distinct user roles - Coordinator, Resource, and User. Within my form, there are several controls that need to be disabled or set to read-only based on the user role, specifically for the User role while remaining ...

Merge JSON object information into tables, including column headings

I am currently facing a challenge in loading multiple JSON files into tables within different divs. Here is the structure of my JSON data: JSON file 1: [ { "id": 12345, "code": "final", "error": "", "data": [ ...

Error: Unable to access the 'prototype' property of an undefined object (inherits_browser.js)

After updating our app to a newer version of create-react-app, we started encountering the following error: This error seems to be related to inherits_browser.js, which is likely from an npm module that we are unable to identify. The line in error within ...

What is preventing me from binding ng-click to my element?

I've encountered an issue where the ng-click event is not activating on my element. Despite using the in-line controller script as shown below, I am unable to trigger my alert. Are there any integration issues that I should be mindful of? What could p ...

Guide to triggering an event when two distinct keys are pressed simultaneously (Using HTML5 and Javascript)

I'm looking to have my character jump whenever I press any key on the keyboard. Is there a method to achieve this using "case..." functions? Thanks! Jordan ...

Vue.js: Issue with dynamically calculating class property

I am attempting to create a computed class in vue.js 2.0 using the following syntax: <li :class="'str1' calcStarClass(1, p.rtg)"> </li> In my methods section, I have the foll ...

Using makeStyles() in MUI for conditional rendering

Trying to dynamically change the value of backgroundColor under the property "& + $track" using props.disabled but it seems that MUI does not recognize it. Why could that be? const useStyles = makeStyles((theme) => ({ root: { overflow: "vis ...

Rest parameter ...args is not supported by Heroku platform

When interacting with Heroku, an error message SyntaxError: Unexpected token ... appears. What modifications should be made to this function for compatibility with Heroku? authenticate(...args) { var authRequest = {}; authRequest[ ...

Tips for recognizing hyperlinks within a block of text and converting them to clickable links in Angular 2

My task is to create clickable links within a paragraph of strings. I tried using a custom pipe, but seem to be missing something essential. Here's my attempt: import { Pipe, PipeTransform } from '@angular/core'; import { DecimalPipe ...

javascript calculate average based on user input array

There is a problem that I am trying to solve, but as a beginner it seems quite challenging. Here is the code I have written so far, however, when I run it only one window appears. Any advice or guidance would be greatly appreciated. var years = prompt(" ...

Issue arises when attempting to render a component while utilizing window.location.pathname and window.location.hash in conjunction with a navigation bar

I am encountering a problem when attempting to render a react component using a navigation bar. I have experimented with both Switch case and if-statement methods. The first approach involves using window.location.hash, which successfully alters the URL u ...

Troubleshooting: Issues with the functionality of ng-include in AngularJS

Hi there, I am new to angular js and I'm attempting to integrate a simple html file into my page. Below is the code I am using: <!DOCTYPE html> <html ng-app=""> <head> </head> <body ng-controller="userController"> < ...

The process of converting a response into an Excel file

After sending a request to the server and receiving a response, I am struggling with converting this response into an Excel file. Response header: Connection →keep-alive cache-control →no-cache, no-store, max-age=0, must-revalidate content-dispositio ...

Components can be iterated over without the use of arrays

In my component, I have a render that generates multiple components and I need some of them to be repeated. The issue I am facing is that when I create an HTML render, the variable is not being processed and it just displays as text. Although the actual c ...

How can I invoke a PHP script using AJAX?

I am currently working on implementing a feature that involves multiple tables where users can move table rows between the tables. I want to use ajax to call a php script that will update the database with the new values, specifically assigning a new paren ...

Error in returnTo behavior. The URL is being deleted just before making the post request

I have implemented express-session and included a middleware that assigns the value of req.session.returnTo to the originalUrl. router.post( '/login', passport.authenticate('local', { failureFlash: true, failureRedirect: &ap ...