我有一个应用程序有很多东西可以级联保存,成像一个普通的主 - 详细视图。
在这个视图中,我有一个" Save All"保存迭代中每一行的按钮,触发jQuery自定义事件,序列化保存操作并防止生成不受控制的请求队列。
每次保存一行时,程序会递减计数器并启动新行的保存。
当没有要保存的行(counter = 0)时,Everithing结束。
这是执行此操作的代码段:
var save_counter = -1;
// Creates a counter and save content header when finished to save rows.
var updCounter = function(evt){
// Update Counter
save_counter--;
// Register updates When there are not rows to skip
if ((save_counter===0)
|| (save_counter===0 && edit_status == "modified") ){
console.log('Persist Master');
$(document).trigger('save_ok');
}
};
saveRows = $(form_sel);
// Reset Save Counter
save_counter = saveRows.length;
// Iterate through lines
saveRows.each(function(idx){
var form = $(this);
// Execute Uptade Counter once
form.one(update_counter, updCounter);
// Per each performed save, decrese save counter
form.trigger('submit');
});
现在我正在使用angular迁移一些关键的应用程序模块,但我不知道这样做。
最佳做法是执行批量请求调用吗?
使用$ scope变量和$ watch是一个好主意,使用类似的东西吗?
var RowController = angular.controller('RowController', function($scope, $http){
$scope.rows = [
{id : 1, title : 'lorem ipsum'}
, {id : 2, title : 'dolor sit amet'}
, {id : 3, title : 'consectetuer adipiscing elit'}
];
// Counter Index
$scope.save_counter = -1;
// "Trigger" the row saving, changing the counter value
$scope.saveAll = function () {
$scope.save_counter = 0;
};
// Watch the counter and perform the saving
$scope.$watch('save_counter', function(
// Save the current index row
if ($scope.save_counter >= 0
&& $scope.save_counter < $scope.rows.length) {
$http({
url : '/row/' + $scope.rows[$scope.save_counter].id,
data: $scope.rows[$scope.save_counter]
}).success(function(data){
// Update the counter ...
$scope.save_counter ++;
}).error(function(err){
// ... even on error
$scope.save_counter ++;
});
};
));
});
答案 0 :(得分:0)
以下是一个例子:
app.factory('RowService', function($http, $q) {
return {
saveRow: function(row) {
return $http({
url: '/row/' + row.id,
data: row
});
},
saveAll: function(rows) {
var deferred = $q.defer();
var firstRow = rows.shift();
var self = this;
// prepare all the saveRow() calls
var calls = [];
angular.forEach(rows, function(row) {
calls.push(function() {
return self.saveRow(row);
});
});
// setup the saveRow() calls sequence
var result = this.saveRow(firstRow);
angular.forEach(calls, function(call) {
result = result.then(call);
});
// when everything has finished
result.then(function() {
deferred.resolve();
}, function() {
deferred.reject();
})
return deferred.promise;
}
}
});
在你的控制器上:
app.controller('RowController', function($scope, RowService) {
...
$scope.saveAll = function() {
// $scope.rows.slice(0) is to make a copy of the array
RowService.saveAll($scope.rows.slice(0)).then(
function() {
// success
},
function() {
// error
})
};
});
查看此plunker以获取示例。