简体   繁体   English

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

[英]How to close angular-ui modal after click button but under condition

I would like to close modal after click button save, but only when function which is also called by this button is resolved successfully. 我想在单击按钮保存后关闭模态,但仅当成功解析了此按钮调用的功能时。

parent.controller.js 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 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 附加测试modal.html

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

Is it possible this way or maybe I should share scope and just call this function from scope parent and then close under condition? 是否有可能这样或者我应该共享范围并从范围父级调用此函数然后在条件下关闭?

There are two options can think of assuming addTest returns promise. 假设addTest返回promise,有两种选择可以想到。

  1. Move addTest logic to service and call this method from modal controller 将addTest逻辑移动到服务并从模态控制器调用此方法
  2. Pass addTest function as resolve parameter to modal. 将addTest函数作为解析参数传递给modal。 Please refer https://angular-ui.github.io/bootstrap/#!modal 请参考https://angular-ui.github.io/bootstrap/#!modal

Parent

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

Modal 语气

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

.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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