我有一个HTML按钮,必须根据范围变量启用或禁用。AM根据条件为每个条件启用/禁用操作。对于这种情况,我需要$timeout
。
vm.isDisable = true;//disbles the button before forEAch
//vm.gridData, which is array of object haves more than 1000 rows
angular.forEach(vm.gridData,function(rows){
if(rows.isSelectedRow == true) {
$timeout(function(){
vm.gridApi.selection.selectRow(rows);
})
});
vm.isDisable = false; //enables the button after for each
,但由于foreach内部的$timeout
,在每个完成之前都可以启用按钮。我如何在foreach期间禁用按钮并在迭代后启用它。
您应该使用all
方法使用承诺:
var promises = [];
vm.isDisable = true;
angular.forEach(vm.gridData,function(rows){
if(rows.isSelectedRow == true) {
var deferred = $q.defer();
promises.push(deferred.promise);
$timeout(function(){
vm.gridApi.selection.selectRow(rows);
deferred.resolve();
})
});
$q.all(promises).then(function(){
vm.isDiable = false;
});
$timeout
返回诺言,因此您可以创建这些承诺的数组,并在他们全部解决后启用按钮
var promises = vm.gridData.reduce(function(a, c) {
if (c.rows.isSelectedRow == true) {
a.push($timeout(function() {
return vm.gridApi.selection.selectRow(c.rows);
}));
}
return a;
}, []);
$q.all(promises).then(function(){
vm.isDiable = false;
})