2014-12-04 34 views
1

我使用$modal.open({...})方法打开UI-Bootstrap模态。当用户按下后退按钮时,我需要关闭它。检测控制器内的ui路由器状态更改并相应地关闭模态

open()方法返回的result诺言在这种情况下无用,因为它无法检测到由于后退按钮导致的状态更改。现在当按下后退按钮时,状态会改变,但模态保持打开状态。

基本上我具有的确切问题是this question,但即使它有一个选定的答案,问题也没有解决从评论中证明的问题。 This other question是类似的,但也不能解决后退按钮问题。

我需要某种方式来检测当前状态是否已从控制器内部发生变化,并调用$modalInstance.close()$scope.$close()方法。

我可以听$stateChangeStart事件并检查fromState参数以有条件地关闭模态。但是,这个事件会不必要地为所有后来的状态改变继续触发。

UPDATE:因此,我试着聆听这个事件,并在第一次被解雇后立即注销它。这样我就可以听到后退按钮的状态变化,然后在需要时停止它。模态的最终代码如下:

$stateProvider.state('itemList.itemNew', { 
    url: '/new', 
    onEnter: function($state, $modal) { 
     $modal.open({ 
      templateUrl: "/static/partials/item/form.html", 
      controller: function($http, $scope, $modalInstance) { 
       $scope.editableItem = {}; 
       $scope.saveItem = function(item) { 
        $http.post('/api/item', item) 
        .success(function(data) { 
         $modalInstance.close(data); 
         alert("Saved Successfully"); 
        }).error(function(data) { 
         alert("There was an error."); 
        }); 
       }; 
       //Register listener specifically for the back button :(
       deRegister = $scope.$on('$stateChangeSuccess', 
        function(event, toState, toParams, fromState, fromParams) { 
         if (toState.name === 'itemList' && 
          fromState.name === 'itemList.itemNew') { 
          $modalInstance.close();//Close the modal 
          deRegister();//deRegister listener on first call 
         } 
        } 
       ); 
      } 
     }).result.then(function() { 
      //Promise Resolved, Modal Closed.. So reload 
      $state.go("^", null, { 
       "reload": true 
      }); 
     }, function() { 
      //Promise Rejected, Modal Dismissed.. no reload 
      $state.go("^"); 
     }); 
    }, 
}); 

我仍然认为应该有更好的方法来做到这一点。 Constellates显然决定从ui-bootstrap转储modal.js。我是否应该这样做,并简单地使用普通Bootstrap CSS中的模式渲染<ui-view/>

回答

5

我需要解决同样的问题。也许稍有不同的设置,但我相信它可能适合你。

我正在使用angular-modal-service,我相信它在bootstrap上运行。

控制器的模式里面我用了以下内容:

$scope.$on('$stateChangeStart', function() { 
    $scope.stateChange(); 
}); 

$scope.stateChange = function() { 
    // Manually hide the modal using bootstrap. 
    $element.modal('hide'); 
    // Now close as normal, but give 500ms for bootstrap to animate 
    close('', 500); 
}; 

第二个功能是刚下退出模式为每docs的手工方式“我不希望使用'按钮上的'data-dismiss'属性,我怎样手动关闭模式?“。它说:

所有你需要做的是抓住你的控制器中的模态元素,然后调用引导模态函数手动关闭模态。然后调用关闭功能正常

所以,现在,如果状态发生变化(包括用户启动的后退按钮单击),模式将优雅地拉开。