簡體   English   中英

angularJS:僅在方法完成后發送window.alert

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM