3

在我的ui-bootstrap模态控制器中,我监视变量。它看起来是这样的:在模式上定义的调用函数在ui-bootstrap模态关闭中

main.controller('modalCtrl', ['$scope', '$rootScope', '$modalInstance', 
 
    function ($scope, $rootScope, $modalInstance) { 
 

 
     var unregister = $rootScope.$watch(function() { return $rootScope.someVariable; }, 
 
          function (newVal) { 
 
           if (newVal == false) { 
 
            $scope.closeModal(); 
 
           } 
 

 
          }); 
 
     $scope.closeModal = function() { 
 
      unregister(); 
 
      $modalInstance.dismiss('cancel'); 
 
     }; 
 
}]);

当我解雇模式我想注销$看,当我做到这一点的NG-点击=“closeModal()”中的HTML它工作正常。但是当我在ESC模式之外点击模式时,它不起作用。那么有没有办法在解雇时调用我的取消注册功能。我知道modal.result.then(close(),dismiss());但如果没有必要,我不想把这个func放到parent $ scope中。

回答

2

只需添加一个更多然后回调到result承诺与unregister

main.controller('modalCtrl', ['$scope', '$rootScope', '$modalInstance', function ($scope, $rootScope, $modalInstance) { 

    var unregister = $rootScope.$watch(function() { 
     return $rootScope.someVariable; 
    }, function (newVal) { 
     if (newVal == false) { 
      $scope.closeModal(); 
     } 
    }); 

    $scope.closeModal = function() { 
     $modalInstance.dismiss('cancel'); 
    }; 

    $modalInstance.result.then(null, unregister); 
}]); 

在这种情况下unregister将两个closeModal和ESC键来调用。顺便说一句,您可以一起摆脱$scope.closeModal,并在模板中使用ng-click="$dismiss('cancel')"

+0

非常感谢。我不知道$ modalInstance具有结果保证。我认为结果承诺只在父范围的模态变量上。 – user3506697

+0

'$ modalInstance'是'$ modal.open'返回的内容。 – dfsq

0

首先,你真的不应该在$rootScope上存储任何东西 - 特别是一个用来关闭你的模态的监视变量。你想通过一些观察变量来关闭你的模态,你试图解决什么问题(以及你想要完成的是什么UX)?这对我来说没有通过气味测试,而且在您的预期设计中有些奇怪。其次,关于不想使用已解决的承诺的说法毫无意义。当你打电话给$modal.open(options)时,它会返回一个对象,比如说modalInstance,然后你可以调用你的承诺回调函数。因此,承诺回调与您的modalInstance以及您可能通过options传递的任何数据存在于相同的上下文中。

有关如何正确使用$modal服务的示例,请参阅我们的文档here