How to get back to before dirty state of an object in AngularJS

592 views Asked by At

I would like to know if there is a way in AngularJS to get back the state of an object before it was made dirty.

I have a simple use case in which I have an edit, save an cancel button. If somebody clicks on the edit button, gets the state of object in question dirty and then click then cancel button, I would like the state of the object back to its previous state(the state before it got dirty).

At the moment when I click on the cancel button, the state of the objects looks changed even when it actually hasn't.

Could I achieve it somehow with some feature provided with AngularJS?

Code relating to the given post:

Code in controller:

$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>
1

There are 1 answers

4
Mohammad Sepahvand On

You need to keep a copy of the original object lying about, use angular.copy():

$scope.originalItem=null;
$scope.onEdit = function(item){
   $scope.originalItem = angular.copy(item);
   $scope.item = item;
}

$scope.onEditCancel=function(){
   $scope.item = $scope.originalItem;
   $scope.originalItem=null;
}