在AngularUI模式打开时暂停执行

时间:2015-06-27 21:08:35

标签: angularjs angular-ui angular-ui-bootstrap

我循环浏览AngularJS中的一些项目,并使用AngularUI模式询问用户对每个项目的输入。我的问题是循环完成并且所有模态立即渲染,而不等待用户。

如何在模态关闭之前等待执行?

我的代码示例:

var listofitems = somelist;
// loop through each item
for (var i in listofitems){
    if (listofitems[i].id == presetId){
        // ask user confirmation in a modal
        $scope.selections = {'doThis': doThis,
                             'doThat': doThat}
        var openModal = function () {
            var modalInstance = $modal.open({
                 templateUrl: 'confirmationModal.html',
                 controller: confirmationController,
                 resolve: {
                     selections: function () {
                          return $scope.selections;
                     }
                 }
            });

            modalInstance.result.then(function (selections) {
                doThis = selections.doThis;
                if (selections.doThat){
                   doThis = selections.doThis;
                }
          });
        }
        // open the modal
        openModal();                                                
      }
   }
}


var confirmationController = function ($scope, $modalInstance, selections) {

    $scope.selections = selections;

    $scope.doThis = function () {
        $scope.selections.doThis = true;
        $modalInstance.close($scope.selections);
    };

    $scope.doThat = function () {
        $scope.selections.doThat = true;
        $modalInstance.close($scope.selections);
    };
};

在这里加入@dsfg答案是Plunkr example。 ui模式不能很好地工作,但您可以在用户提交任何输入之前看到执行已完成。

1 个答案:

答案 0 :(得分:2)

你不能只是暂停循环(你可以使用ES6生成器)。但是您可以更改迭代数组/对象键的方式。你可以做的是使用函数逐个检查项目,并仅在前一个完成时执行下一个“迭代”。承诺很容易。

首先,让openModal返回promise,然后创建将为键数组中的每个项调用的辅助函数checkItems

var openModal = function() {
    var modalInstance = $modal.open({
        templateUrl: 'confirmationModal.html',
        controller: confirmationController,
        resolve: {
            selections: function() {
                return $scope.selections;
            }
        }
    });

    return modalInstance.result.then(function(selections) {
        doThis = selections.doThis;
        if (selections.doThat) {
            doThis = selections.doThis;
        }
    });
};

var listofitems = somelist;
var keys = Object.keys(listofitems);

(function checkItems() {

    // get the first key and remove it from array
    var key = keys.shift();

    if (listofitems[key].id == presetId) {
        // ask user confirmation in a modal
        $scope.selections = {
            'doThis': doThis,
            'doThat': doThat
        }
        // open the modal
        openModal().then(function() {
            if (keys.length) {
                checkItems();
            }
        });
    }    
})();

在上面的示例中,将检查项目,直到拒绝第一个承诺。如果您想检查所有项目而不管承诺状态如何,请使用

openModal().finally(function() {
    if (keys.length) {
        checkItems();
    }
});
相关问题