AngularJs异步问题

时间:2017-07-25 09:20:13

标签: angularjs asynchronous

如何在完成所有异步调用时停止某项功能? 我在列表中有一个foreach,通过异步调用增加一个var(if if condition)

我的代码:

$scope.updateDureePeriodeList = function () {

        var mttLoyer = 0

        angular.forEach($scope.articleListDuree, function (value, key) {
            if (value.selected) {
                if (value.bOption) {
                    $scope.getTauxDevisRevOption(value.prixArt * value.qttArt).then(function (taux) {
                        mttLoyer += value.prixArt * value.qttArt * taux / 100;
                    })
                }
                else
                    mttLoyer += value.prixArt * value.qttArt * $scope.DureeEdit.taux / 100;
            }

        });

        $scope.DureeEdit.periodeList = new Array();
        $scope.DureeEdit.periodeList.push({
            'numPeriode': 1,
            'mttLoyer': parseFloat(mttLoyer).toFixed(2),
        });
}

问题:getTauxDevisRevOption是异步的,当我进入它时,我的函数不会停止,所以在mttLoyer在异步调用的.then()中递增之前它会在$scope.DureeEdit.periodeList.push结束...

2 个答案:

答案 0 :(得分:1)

以下内容可以帮助您

{PK: b, RK: 1, LeftHand: 9999, RightHand: 1000, LeftLeg: 11, Head: h} 

答案 1 :(得分:0)

失去一些头发后,我终于找到了我要求的解决方案! 使用$ q.all是关键。 我的工作代码:

$scope.updateDureePeriodeList = function () {
        var mttLoyer = 0
        var allQ = [];

        angular.forEach($scope.articleListDuree, function (value, key) {
            if (value.selected) {
                if (value.bOption) {
                    allQ.push($scope.getTauxDevisRevOption(value.prixArt * value.qttArt).then(function (taux) {
                        mttLoyer += value.prixArt * value.qttArt * taux / 100;
                    }));
                }
                else
                    mttLoyer += value.prixArt * value.qttArt * $scope.DureeEdit.taux / 100;
           }

        });

        $q.all(allQ).then(function(data){
            $scope.DureeEdit.periodeList = new Array();
            $scope.DureeEdit.periodeList.push({
                'numPeriode': 1,
                'nbrEch': nbrEch,
                'mttLoyer': parseFloat(mttLoyer).toFixed(2),
            });
        });
}

希望以后可以帮助别人!