[英]angularJS: window.alert only after method is done
In my controller with the help of service i'm sending some qr-data to users so: 在控制器的帮助下,我正在向用户发送一些二维数据,因此:
$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.');
}
}
and i see some strange behaviour: it always show warning alert, even if method is done succesfully - i think it is of promisses. 而且我看到一些奇怪的行为:即使方法成功完成,它也始终显示警告警报-我认为这是正确的。 But how could i show window in my case only after servise promisse is returned?
但是,只有在退回服务承诺后,如何才能显示我的窗口?
Hope one of the following helps 希望以下帮助之一
1) Try looking at the following post: $success call back function from AngularJS 1)尝试看以下文章: AngularJS的$ success回调函数
Its a similar question and the following js fiddle might help: http://jsfiddle.net/E5HGy/6/ 它是一个类似的问题,以下js小提琴可能会有所帮助: http : //jsfiddle.net/E5HGy/6/
2) A counter as stated above would also solve the problem, something such as 2)如上所述的计数器也可以解决问题,例如
if(i == selector.length)
// "callback"
would essientially solve it 会实质性地解决它
In order to do this with promises, you need to create a counter that checks every time a user is updated, and then triggers the alert once all are accounted for. 为了兑现承诺,您需要创建一个计数器,该计数器会在每次更新用户时进行检查,然后在计入所有费用后触发警报。
$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()
happens on every promise, that's where you want to add your counter incrementation. .finally()
发生在每个promise上,这就是您要添加计数器增量的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.