[英]angularJS: window.alert only after method is done
在控制器的帮助下,我正在向用户发送一些二维数据,因此:
$scope.sendtoList = function () {
$scope.qrStatus = false;
angular.forEach($scope.users, function (item) {
if (item.Selected){
inviteService.sendQR(item.Emails.main, $scope.company.Id).then(function(response) {
$scope.qrStatus = true;
},
function(err) {
$scope.qrStatus = false;
});
}
});
if ($scope.qrStatus){
$window.alert('QR-code has been sended successfully.');
}
else{
$window.alert('Warning! QR-code has not been sended successfully.');
}
}
而且我看到一些奇怪的行为:即使方法成功完成,它也始终显示警告警报-我认为这是正确的。 但是,只有在退回服务承诺后,如何才能显示我的窗口?
希望以下帮助之一
1)尝试看以下文章: AngularJS的$ success回调函数
它是一个类似的问题,以下js小提琴可能会有所帮助: http : //jsfiddle.net/E5HGy/6/
2)如上所述的计数器也可以解决问题,例如
if(i == selector.length)
// "callback"
会实质性地解决它
为了兑现承诺,您需要创建一个计数器,该计数器会在每次更新用户时进行检查,然后在计入所有费用后触发警报。
$scope.sendQRtoList = function () {
$scope.qrStatus = false;
var count = 0;
var length = $scope.users.length;
var error = 0;
angular.forEach($scope.users, function (item) {
if (item.Selected){
inviteService
.sendQR(item.Emails.main, $scope.company.Id)
.then(function(response) {
//yay!
},
function(err) {
error++;
})
.finally(function () {
count++;
if (count === length && error === 0) {
$window.alert('QR-code has been sent successfully.');
}
if (count === length && error !== 0) {
$window.alert('Warning! QR-code has not been sent successfully.')
}
});
}
});
};
.finally()
发生在每个promise上,这就是您要添加计数器增量的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.