gpt4 book ai didi

javascript - 如何回到 AngularJS 中对象的脏状态之前

转载 作者:行者123 更新时间:2023-11-30 17:09:10 26 4
gpt4 key购买 nike

我想知道 AngularJS 中是否有一种方法可以在对象变脏之前取回对象的状态。

我有一个简单的用例,其中有一个 editsave 和一个 cancel 按钮。如果有人点击编辑按钮,将有问题的对象状态弄脏,然后单击然后取消按钮,我希望对象的状态回到它以前的状态(变脏之前的状态)。

当我点击 cancel 按钮时,对象的状态看起来发生了变化,但实际上并没有发生变化。

我能否通过 AngularJS 提供的某些功能以某种方式实现它?

与给定帖子相关的代码:

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 代码:

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

最佳答案

您需要保留原始对象的副本,使用 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;
}

关于javascript - 如何回到 AngularJS 中对象的脏状态之前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27356802/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com