1

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>
skip
  • 12,193
  • 32
  • 113
  • 153

1 Answers1

2

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;
}
Mohammad Sepahvand
  • 17,364
  • 22
  • 81
  • 122
  • For some reason, it did not work. I have updated the post with relevant code. Could you please have a look at it? Thanks. – skip Dec 08 '14 at 12:03
  • When debugging with debugger, I could see the value being changed to previous one but doesn't show that change in the view. – skip Dec 08 '14 at 12:38
  • I will get back to it in a couple of days. Its basically a row in a table am trying to edit/cancel. – skip Dec 09 '14 at 14:23
  • Hey Mohammad, here is the plunker http://plnkr.co/edit/ivMwHzcj320z6cTaILbR?p=preview. Thanks. – skip Dec 25 '14 at 16:48