Restoring an object to its previous clean state in AngularJS

Is there a way to restore the original state of an object in AngularJS after it has been modified?

In my scenario, I have an edit, save, and cancel buttons. When a user clicks on edit, the object's state changes, but if they then click cancel, I want the object to revert back to its previous unperturbed state.

Currently, when clicking cancel, the object appears changed even though it is not.

Is there a feature in AngularJS that can help me achieve this functionality?

Related Code:

Controller Code:

$scope.uneditedObject = null;
$scope.handleEdit = function(state, index) {
    $scope.uneditedObject = angular.copy($scope.objects[index]);
    $scope.state = state;
    $scope.index = index;
    if(state == 'VIEW') {
        $scope.objects[index] = $scope.uneditedObject
        $scope.uneditedObject = null;
    }
}

HTML Code:

<tr ng-repeat="object in objects">
    <td ng-class="{'editing': $index == index}" >
        {{object.name}}
    </td>
    <td >
        <input type="text" numbers-only class="form-control" ng-model="object.discount" >
    </td>
    <td  ng-class="{'editing': $index == index}" >
        <a class="btn btn-sm red" ng-click="handleEdit('EDIT', $index)" ng-show="state != 'EDIT'">
            Edit
        </a>
        <a class="btn btn-sm blue" ng-show="state == 'EDIT'" ng-show="state != 'EDIT'" ng-click="update(...)">
            Save
        </a>
        <a class="btn btn-sm default" ng-show="state == 'EDIT'" ng-click="handleEdit('VIEW', $index)">
            Cancel
        </a>
    </td>
</tr>

Answer №1

To ensure you have a duplicate of the initial object available, employ angular.copy():

$scope.initialObject = null;
$scope.onEdit = function(object){
   $scope.initialObject = angular.copy(object);
   $scope.object = object;
}

$scope.onEditCancel=function(){
   $scope.object = $scope.initialObject;
   $scope.initialObject = null;
}

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

Utilizing nested arrays to implement v-for loop for efficient data rendering

Within my array - 'items', each object contains another array of objects. I am trying to retrieve the second array called 'productPrices' in order to use v-for. However, items.productPrices is not working for me. Do I need to implement ...

Navigating to the most recent item within ng-repeat (AngularJS or JavaScript)

I am working on a feature where posts are displayed using ng-repeat in a div, and users can enter new posts in an input box. The posts are sorted so that the latest one appears at the bottom. After adding a new post, I want to automatically scroll down t ...

Converting important information from elements in an Array into a string separated by commas

Which lodash method or function is best suited for extracting the ids from the array below and creating a comma-separated string out of them? var myArray = [ { tag: 'wunwun', id: 132 }, { tag: 'davos&apos ...

Attempting to create a function that runs other functions

Is there a way to call a JavaScript function from a PHP file using AJAX and the GET method? I attempted to achieve this by including <script type="text/javascript"> callFunction(); </script> but it did not work as expected. Is there an altern ...

Unable to get the sublocality dropdown list to cascade properly in asp.net mvc

I am dealing with three dropdown lists. The initial action method for the City dropdown is shown below: public ActionResult Create() { List<SelectListItem> li = new List<SelectListItem>(); li.Add(new Sel ...

Confirming the structure of a URL using JavaScript/jQuery

I have a text field where users input URLs. I need to validate the format of the URL using regular expressions. Specifically, I am looking for invalid URLs such as: http://www.google.com//test/index.html //Invalid due to double slash after hostname http: ...

Exploring the capabilities of hosting a Postgre database on the Heroku

Currently, I am in the process of developing an API using Swagger on Heroku and I want to verify if the endpoints are correctly creating entries in the Postgre Database. However, when attempting to connect to Heroku's Postgre in my testing environment ...

Button that vanishes when clicked, using PHP and HTML

I am in the process of creating an online store and I am seeking to implement a button that directs users to a new page, but then disappears permanently from all pages within the store. Here is the code snippet I have developed so far: <input class="b ...

Designate material for a particular table header element

Is there a method to pass content within a td-element to a specific th-element? I am working with a dynamic table and need to associate the content correctly under each table header. I have implemented pagination for the rows in the table. Currently, all ...

Tips for seamlessly incorporating advertisements into a mixed application

I am having trouble adding banner ads to my hybrid application developed with Telerik. Despite my extensive research, I have been unable to find a suitable solution. Is there any html5 or javascript banner advertising service/API that is compatible with ...

What is the best way to stop a jQuery function from applying titles extracted from the first row th's in thead's to multiple tables in a document?

My circumstances: I am new to jQuery and Stack Overflow, seeking assistance for my website project. The challenge: Building a website using Bootstrap 3.3.6 with intricate data tables that need to be stacked dynamically on mobile devices using CSS. It is c ...

There seems to be an issue with displaying the meta information in a Nuxtjs project using this.$

I am facing an issue with meta information in a Vue page. When I try to access "this.$route.meta", it does not display any meta information. However, when I inspect the Vue page element, I can see that there is indeed meta information present. How can I ...

Error: Attempted to save data with mongoose but encountered an Uncaught ReferenceError; `amadeus` is not defined at line 16,

When attempting to store data in mongoDB using mongoose, an error was encountered. The code snippet from index.js is as follows: const mongoose = require('mongoose') mongoose.connect('mongodb://127.0.0.1:27017/myapp') .then(() => ...

Adding data to an array using V-Bind in VueJS

I am currently working on a project that involves retrieving data from multiple devices and displaying the data on a chart in real-time. The goal is to update the chart every second as new data comes in. Below is the code snippet I have been using: index ...

Assistance with Javascript and Jquery for Wordpress

Here's a snippet of my JavaScript code: jQuery(document).ready(function() { jQuery.wiseguys(); }); // To safely use the "$" sign, we are using a plugin structure (function($) { // This is the class constructor or "init" function $.wiseguys = fun ...

Most Effective Method for Directing Users to Mobile Website

How do you prefer to guide users to a custom mobile site, such as redirecting from mysite.com to m.mysite.com or mysite.com/m? I previously experimented with the Detect Mobile Browsers JS solution, which seemed promising. However, I noticed that it initia ...

Dispose of jQuery instance when it is no longer required

Encountered an issue with jQuery: There are multiple div containers on a page with the class "stackgo" and different data attributes. For example: <div class=\"stackgo\" data-an=\"HEY\" data-ms=\"HO\" data-me=\"HM&bso ...

AngularJS Circular Dependency - Metamorphosis

Seeking advice on dealing with nested resources in an API. I am creating "transformers" to format data for better usability. However, I am facing a circular dependency issue due to the nature of nested resources and bidirectional relationships. For examp ...

Utilizing Jquery for an AJAX call incorporating Odata into the request

I've encountered a challenge while developing a small application to search for data within the Odata dataset from KVK (the Dutch chamber of commerce). The goal is to retrieve information based on file numbers, ZIP codes, or tradenames. Here is an ex ...

What strategies can be implemented to minimize the use of if-else statements?

Is there a more efficient way to simplify this if-else statement? This code dynamically changes the picture based on integers retrieved from the database. I am looking for ways to optimize this code. if (val["soil_h"] < 21){ $("#ground").att ...