[英]How can I update data in a for loop when my data is returned with a defer after the loop completes
I have two arrays: 我有两个数组:
$scope.grid.data and $scope.grid.backup
I use the following script to compare the data in each one element at a time: 我使用以下脚本来一次比较每个元素中的数据:
for (var i = 0, len = $scope.grid.data.length; i < len; i++) {
if (!angular.equals($scope.grid.data[i], $scope.grid.backup[i])) {
var rowData = $scope.grid.data[i]
var idColumn = $scope.entityType.toLowerCase() + 'Id';
var entityId = rowData[idColumn];
entityService.putEntity($scope.entityType, entityId, $scope.grid.data[i])
.then(function (result) {
angular.copy(result, $scope.grid.data[i]);
angular.copy(result, $scope.grid.backup[i]);
}, function (result) {
alert("Error: " + result);
})
}
}
and the following to update the database: 然后执行以下操作以更新数据库:
putEntity: function (entityType, entityId, entity) {
var deferred = $q.defer();
EntityResource.putEntity({ entityType: entityType, entityId: entityId }, entity,
function (resp) {
deferred.resolve(resp);
}, function (resp) {
deferred.reject('Error updating');
});
return deferred.promise;
}
This script correctly notices the changes and updates the database. 该脚本正确地注意到更改并更新数据库。
However there is a problem when the putEntity returns with a result and it then tries to copy the result into $scope.grid.data[i] and $scope.grid.backup[i] 但是,当putEntity返回结果并尝试将结果复制到$ scope.grid.data [i]和$ scope.grid.backup [i]时,会出现问题。
This happens later and when it tries to do this it always tries to put it into element 11. 这种情况稍后发生,并且在尝试执行此操作时,总是尝试将其放入元素11中。
Does anyone have any ideas how I can ensure the returned data from putEntity is copied back into the correct element of the grid.data and grid.backup arrays? 有谁知道我如何确保从putEntity返回的数据被复制回grid.data和grid.backup数组的正确元素中?
You need to create a closure over i. 您需要在i上创建一个闭包。 What you can do is create a function
您可以做的就是创建一个函数
var updateGridData=function(entityType, entityId, gridDataToUpdate, gridIndex)
entityService.putEntity(entityType, entityId,gridDataToUpdate)
.then(function (result) {
angular.copy(result, $scope.grid.data[gridIndex]);
angular.copy(result, $scope.grid.backup[gridIndex]);
}, function (result) {
alert("Error: " + result);
})
}
So your main method becomes 所以你的主要方法变成
for (var i = 0, len = $scope.grid.data.length; i < len; i++) {
if (!angular.equals($scope.grid.data[i], $scope.grid.backup[i])) {
var rowData = $scope.grid.data[i]
var idColumn = $scope.entityType.toLowerCase() + 'Id';
var entityId = rowData[idColumn];
updateGridData($scope.entityType, entityId, $scope.grid.data[i],i);
}
}
You can get some more idea from this question JavaScript closure inside loops – simple practical example 您可以从这个问题中了解更多关于循环内JavaScript闭合的想法–简单的实际示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.