How to implement 'cancel changes' feature in AngularJS with the use of splice method

In my datagrid, I am displaying data from an array called listOfAttributes. Each row has an edit icon which, when clicked, reveals two buttons: save and cancel edit. The issue I am facing is that when a user clicks on cancel edit, the updated data should be cleared and the previously existing data should persist. I have tried using the splice method to add the previous object and delete the current one at the same time, but it does not seem to work as expected.

 $scope.edit = function(attribute) {
    angular.copy(attribute, $scope.copyAttr);
 }

$scope.save = function(attribute){
  // works fine;
}

 $scope.cancelEdit = function(attribute) { // doesn't work

    var indx = $scope.listOfAttributes.indexOf(attribute);

    $scope.listOfAttributes.splice(indx, 0, $scope.copyAttr);
    $scope.listOfAttributes.splice(indx,1);

} 

Answer №1

After inserting copyAttr at position indx in the array listOfAttributes, it is then immediately removed.

listOfAttributes = ['X', 'Y', 'Z'];
listOfAttributes.splice(1, 0, 'W'); // X, W, Y, Z
listOfAttributes.splice(1, 1);      // X, Y, Z

To replace the item at index indx, you can achieve this with a single call to splice:

$scope.listOfAttributes.splice(indx, 1, $scope.copyAttr);

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

Effortless Like/Unlike feature with a text button option enhanced with ajax functionality and

Struggling to create a simple Like/Unlike button in PHP without refreshing the page. Despite an abundance of tutorials on AJAX and jQuery, implementation remains elusive due to lack of experience. Uncertain where each part of the code goes within which fil ...

Attempting to extract decibel levels from an audio file using JavaScript

I've been exploring the details provided here: Is there a way get something like decibel levels from an audio file and transform that information into a json array? However, when attempting to execute the JSBin snippet below, I encountered some conf ...

How to prevent page refresh when hitting enter in jQuery form?

Currently, my form does not refresh the page when I click the button to submit it. However, if I press Enter while a text input is selected, the page will refresh. Is there a way to make pressing Enter on the text input perform the same action as clicking ...

Arranging a 2D array of matchups to ensure an equal distribution of home and away matches for each team

I am in the process of developing a unique UEFA Champions League 24 'Swiss Model' tournament with 36 teams. Each team is set to compete against 8 different opponents, resulting in a total of 144 matches. I already have a list of matchups prepared ...

"Exploring the possibilities of Ajax in conjunction with Sol

I recently completed a tutorial on Ajax Solr and followed the instructions in step one. Below is the code I wrote: header.php: <script type="text/javascript" src="static/js/ajax-solr/core/Core.js"></script> <script type="text/javascript" s ...

Loop through an array of arrays in JavaScript. If a match is found, add it to an existing inner array. If not, create a new

I am currently extracting data from a database, and here is a simplified representation of the information: var example = [ {'start': 1966, 'end': 1970}, {'start': 1969, 'end': 1971}, {'start&ap ...

In the world of Knockout JS, forget about using e.stopPropagation() because it won't

In my table, I have two actions that can be performed: Click event on the row level and click while checking a checkbox inside that row. However, when the checkbox is checked, I do not want the click event on the row to be triggered. <tbody data-bin ...

What could be the reason behind the model returning null values?

Exploring Angular Service Implementation: app.service('loginService', ['$http', function ($http) { this.userLogin = function (user) { console.log(user); //displays {'username': '<a href="/cdn-cgi/l/email-protectio ...

Adding HTML elements dynamically using jQuery: A how-to guide

My objective is to start with one element upon loading the page, and this element should have an ID of "something_O". When the user clicks on an add link, a new identical HTML element should be added underneath the existing element. The new element should ...

Utilize npm to incorporate external JavaScript libraries into Meteor 1.3

Trying to integrate the OpenSeadragon library into my Meteor app has been a bit challenging. After successfully installing it via npm using meteor npm install openseadragon, I found that the OpenSeadragon docs only offer an example using the script tag. T ...

I am encountering an error with setTimeout(): Timeout { _called: false }

I have been experimenting with creating a function that generates a random number and then adds 5 to it after a 3-second delay This is what I have attempted: const add5 = (randomNum) => { return randomNum + 5 } // Function for you to get start ...

Learn how to create a ReactNative splash screen that is displayed for 5 seconds before automatically disappearing

Currently, I am in the process of developing a splash screen component that should run for a minimum of 5 seconds when the application is launched initially before transitioning to another component or screen. Although I just began learning react-native y ...

What could be causing the Angular HTTPClient to make duplicate REST calls in this scenario?

I am encountering an issue with my Angular service that consumes a Rest API. Upon inspecting the network and the backend, I noticed that the API is being called twice every time: Here is a snippet of my Service code: getAllUsers():Observable<any>{ ...

A guide on extracting data from various HTML elements effectively with JavaScript

I'm searching for a universal technique to extract values from multiple HTML elements. For instance: <div>Experiment</div> <select><option>Experiment</option></select> <input value="Experiment" /> These thr ...

The TypeScript declarations for the scss module are malfunctioning

Just recently, I set up a React project using rollup. Below is the configuration file for my rollup setup: rollup.config.js import serve from "rollup-plugin-serve"; import livereload from "rollup-plugin-livereload"; import babel from &q ...

What could be the reason for my directive not properly interpolating the scope variable?

I attempted to create a directive that would swap out a CSS link with an inline style definition. Check out the functional version here. Now, I am hoping to achieve the same functionality using interpolation, so that I don't have to manually set the ...

Tips for showing an alert when incorrect login credentials are entered on a login form

<?php include('includes/config.php'); if(isset($_POST["submit"])){ $empid=$_POST["empid"]; $pass=$_POST["password"]; $query=mysqli_query($conn,"SELECT employee_id, fname,lname,empid,password, status, role FROM employee where empid='$emp ...

Utilizing Next.js to dynamically load a component library based on the response from getServerSideProps

I am working on a project that involves multi-tenancy and am looking for a way to dynamically switch between component libraries based on an external response while maintaining server-side rendering. Both component libraries have the same structure, includ ...

Partial View fails to render on the webpage

After submitting information from my first partial view, I attempted to load a second partial view. However, upon submission, the first partial view just refreshes and remains on the same page instead of loading the new view. Despite setting up my controll ...

Implementing a dynamic click event for checkboxes in jQuery specifically targets the first checkbox

Currently, I am dealing with multiple ascx controls that contain different areas with checkboxes on each one. Initially, I utilized the following code snippet: $('[type=checkbox]').click ( function(){ code }); and it worked as intended at firs ...