单击按钮后但在条件下如何关闭angular-ui模态

时间:2019-05-06 18:42:28

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

我想在单击按钮保存后关闭模态,但是只有在成功解决了由该按钮调用的函数时,才可以关闭模​​式。

parent.controller.js

.module('app.test')
.controller('TestController', function ($uibModal) {
    let vm = this
    vm.addTest = addTest
    vm.openAddTestModal = openAddTestModal


    function openAddTestModal() {
        var modalInstance = $uibModal.open({
          component: 'AddTestModalComponent',
          windowClass: 'test-modal',
        })
        modalInstance.result.then(function (result) {
            vm.addTest(result);
        });
    }

    function addTest(test) {
        //do something
        if (testCondition) {
            // do something 
               // success - close modal
         } else {
            // error - don't close modal
        }
    }
})

modal.component.js

.component('AddTestModalComponent', {
    templateUrl: 'app/modals/add-test-modal.html',
    controllerAs: 'vm',
    controller: function ($modalInstance) {
        this.testToSave = [''];
        this.save = function (result) {
            $modalInstance.close(result); 
    //close only function called in parent resolve success
        };
    }
})

add-test-modal.html

<button class="btn btn-primary btn-blue" type="submit"
        ng-click="vm.save(vm.test)">
  Save
</button>

是否可以通过这种方式,或者我应该共享作用域并仅从作用域父级调用此函数,然后在条件下关闭?

1 个答案:

答案 0 :(得分:0)

有两个选项可以考虑假设addTest返回promise。

  1. 将addTest逻辑移至服务并从模态控制器调用此方法
  2. 将addTest函数作为解析参数传递给模态。请参阅code example

父母

function openAddTestModal() {
    var modalInstance = $uibModal.open({
        component: 'AddTestModalComponent',
        windowClass: 'test-modal',
        resolve: {
            addTest: addTest
        }
    })
    modalInstance.result.then(function (result) {
        vm.addTest(result);
    });
}

模式

controller: function ($modalInstance, addTest) {
    this.testToSave = [''];
    this.save = function (result) {
        addTest().then(function(){
            $modalInstance.close(result);
        })
    };
}