我正在使用 $resource 来发出休息请求。
我想将结果放入作用域数组中以对其进行修改。
我想知道某个值是否已更改,并在按下取消按钮时删除这些更改。
这是一个 plunker,说明了我想要做什么。
http://plnkr.co/edit/L0AROr58DMRNfU8AX6kX?p=preview
我的问题是,当我修改“$scope.centres”时,“$scope.centresBackup”也被修改!
我不明白为什么,我想知道如何理解背后的机制以及如何做我想要的事情。
* JS *
var RestRequest = $resource('http://maps.googleapis.com/maps/api/geocode/json', null,
{'test' :{
'method' : 'GET',
'params' : {'address':'test'}
}
});
RestRequest.test().$promise.then(function(response) {
$scope.centres = response.results[0].address_components;
$scope.centresBackup = response.results[0].address_components;
});
$scope.$watch('centresBackup', function(newValue, oldValue) {
console.log(newValue);
}, true);
$scope.editCentre = function(i) {
$scope.centres[i].modif = true;
}
$scope.cancelEdit = function(i) {
console.log(i);
console.log('modified = ' + $scope.centres[i].short_name);
console.log('backup = ' + $scope.centresBackup[i].short_name);
$scope.centres[i].modif = false;
//$scope.centres[i] = $scope.centresBackup[i];
}
最佳答案
发生这种情况是因为数组 $scope.centres 和 $scope.centresBackup 对 promise response.results[0].address_components 具有相同的引用,而不是仅使用 = ,您可以尝试使用 angular.copy,如下所示:
$scope.centres = angular.copy(response.results[0].address_components);
$scope.centresBackup = angular.copy(response.results[0].address_components);
我已经在你的plunker中尝试过这个,看起来不错。
关于javascript - 对比编辑后$resource结果修改情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26799040/