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>