Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Angularjs中将数据作为备份字段处理到作用域,以便在请求失败时回滚?_Angularjs - Fatal编程技术网

如何在Angularjs中将数据作为备份字段处理到作用域,以便在请求失败时回滚?

如何在Angularjs中将数据作为备份字段处理到作用域,以便在请求失败时回滚?,angularjs,Angularjs,我有一个数据块,当我编辑其中一个数据块时,我想将该项的当前日期复制到一个类似$scope.backup_字段的范围中,以便在更新失败时能够回滚。正如我下面的代码所示,$scope.backup_字段可以获取我正在编辑的项目数据,但是当更新失败时,我会在我修改的最新数据之后注销$scope.backup_字段 我的代码: $scope.block_data = [ [ {id: 1, name: 'Data 1'}, {id: 2, name: 'Data 2'}

我有一个数据块,当我编辑其中一个数据块时,我想将该项的当前日期复制到一个类似$scope.backup_字段的范围中,以便在更新失败时能够回滚。正如我下面的代码所示,$scope.backup_字段可以获取我正在编辑的项目数据,但是当更新失败时,我会在我修改的最新数据之后注销$scope.backup_字段

我的代码:

$scope.block_data = [
   [
     {id: 1, name: 'Data 1'},
     {id: 2, name: 'Data 2'}
   ],
   [
     {id: 3, name: 'Data 3'}
   ]
];
$scope.backup_field = [[],[],[],[],[],[]];

$scope.editItem = function(_no, index){// _no has value from 0 to 6 
   $scope.backup_field[_no][index] = $scope.block_data[_no][index];
}

$scope.updateItem = function(_no, index){
   $http.post(.....).then(function (response){
       var res = response.data;
       if (res.status === 200){
           //Do something if update successfully
       }else {
          alert('Failed');
          $scope.block_data[_no][index] = $scope.backup_field[_no][index]; //The problem is here, the $scope.backup_field[_no][index] value also change following the data of item that user modified in UI.
       }
   })
}


您必须使用angular.copy进行此操作-

创建源的深度副本,该副本应为对象或数组。 此函数在内部使用,主要用于更改检测 密码它不是一个通用的复制功能,并且具有 以下是一些限制


您是否在onchange上使用了$scope.editItem?没有。我只是用ng click来执行这个函数。你能显示一下你的HTML代码吗。我需要知道你如何调用这些函数。我想我已经解决了你的问题,但我想通过查看你的html代码来确定我是否遵循了piedpiper,它解决了我的问题。谢谢你阅读我的帖子:谢谢,你的想法节省了我的时间
$scope.block_data[_no][index] = angular.copy($scope.backup_field[_no][index]);