简体   繁体   中英

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

Its a similar question and the following js fiddle might help: http://jsfiddle.net/E5HGy/6/

2) A counter as stated above would also solve the problem, something such as

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM