[英]How to get back to before dirty state of an object in AngularJS
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. 我想知道AngularJS中是否有一种方法可以使对象变脏之前恢复其状态。
I have a simple use case in which I have an edit
, save
an cancel
button. 我有一个简单的用例,其中有一个edit
, save
一个cancel
按钮。 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. 当我单击“ cancel
按钮时,对象的状态看起来已经改变,即使实际上没有改变。
Could I achieve it somehow with some feature provided with AngularJS? 我可以通过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: HTML代码:
<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>
You need to keep a copy of the original object lying about, use angular.copy()
: 您需要保留原始对象的副本,使用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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.