销毁以ngDialog模式启动的AngularJS $间隔

时间:2014-04-14 09:26:51

标签: javascript angularjs ng-dialog

我有一个显示数据表的模态。使用$ http和$ interval每隔几秒更新基础数据,但仅在模式显示时才更新。我正在使用ngDialog库作为模态。我需要更新停止模态关闭,但我不知道触发此破坏的最佳方法。一些代码:

$scope.openModal = function() {

var refreshModal = function() {
   $http({
       params: {proj_id: $scope.projectId},
       url: '/projects/_get_data',
       method: 'GET'
   })
   .success(function(data, status, headers) {
       $scope.modalData = data.data;
       $scope.updateModal()           
   })
   .error(function(data, status, headers) {
       console.log('it didnt work');
   }); 
}

refreshModal();

$interval( function() { refreshModal(); }, refreshRate);

ngDialog.open({ template: 'ModalId', scope: $scope, className: 'table-modal', showClose: false });

};

如何检测模态关闭?

感谢。

1 个答案:

答案 0 :(得分:2)

最好的方法是将$ interval的实例传递给模态关闭事件,并在关闭模态时将其杀死。

类似的东西:

var interval = $interval( function() {refreshModal(); }, refreshRate);
var dialog = ngDialog.open(...);
$rootScope.$on('ngDialog.closed', function (e, $dialog) {
     //identify if the dialog instance closing is the one the interval is for
     if ( areTheSame(dialog, $dialog) ){
          $interval.cancel(interval);
     }  
 });

编辑:for @zbycz 另一个更清洁的解决方案是使用对话框具有closePromise

的事实
var interval = $interval( function() {refreshModal(); }, refreshRate);
var dialog = ngDialog.open(...);
dialog.closePromise.then(function(){
    $interval.cancel(interval);
});