通过背景检测关闭$ modal

时间:2014-05-29 19:01:11

标签: angularjs angular-ui-bootstrap

我正在使用AngularJS和angularUI-bootstrap。有没有办法通过点击背景来检测何时关闭模态?我试图根据模态的关闭来改变一个布尔值。

4 个答案:

答案 0 :(得分:3)

当然,通过ESC /点击背景来检测关闭非常容易。如果发生此类事件,result承诺将被拒绝。因此,您可以通过向result方法返回的$modal.open({...})承诺添加错误处理程序来运行您想要的任何逻辑。

你可以在演示页面(http://angular-ui.github.io/bootstrap/)分叉的一个plunker中看到这个:http://plnkr.co/edit/QJbjkB7BUT5VFInVPyrF?p=preview其中$log.info('Modal dismissed at: ' + new Date());代码在模态的解散上执行。

答案 1 :(得分:2)

旧问题,但是如果要在各种关闭操作上添加确认对话框,请将其添加到模态实例控制器中:

$scope.$on('modal.closing', function(event, reason, closed) {
    console.log('modal.closing: ' + (closed ? 'close' : 'dismiss') + '(' + reason + ')');
    var message = "You are about to leave the edit view. Uncaught reason. Are you sure?";
    switch (reason){
        // clicked outside
        case "backdrop click":
            message = "Any changes will be lost, are you sure?";
            break;

        // cancel button
        case "cancel":
            message = "Any changes will be lost, are you sure?";
            break;

        // escape key
        case "escape key press":
            message = "Any changes will be lost, are you sure?";
            break;
    }
    if (!confirm(message)) {
        event.preventDefault();
    }
});

我的右上角有一个关闭按钮,触发“取消”动作。单击背景(如果已启用),将触发取消操作。您可以使用它为各种关闭事件使用不同的消息。这是我这样做的方式,认为这可能对遇到你的问题的其他人有所帮助。

答案 2 :(得分:1)

你可以这样做:

var instance = modal.open({ ... })

instance.result.then(function success(){
 //Do success things
},function fail(reason){
  if( ~reason.indexOf('backdrop') ){ 
    // Do things when modal closes on backdrop click
  }
});

答案 3 :(得分:0)

这是另一种捕捉被拒绝承诺的快捷方式(即模式被故意或通过点击背景而被解雇):

$modal.open({ ... })
.result.catch(function(){
   // do something
});
相关问题