Angularjs 运行$timeout的Cancel函数

Angularjs 运行$timeout的Cancel函数,angularjs,Angularjs,我有以下代码。它每隔几分钟检查一个轮询服务器的工厂。它工作正常,但我想在打开模式时暂停“FetchDataContinous”方法,并在关闭模式时恢复该方法。简而言之,我需要找到一种方法,在打开和关闭modals时切换“fetchDataContinously”。如果我的问题不清楚,请提供建议或让我知道 angular.module('NavBar', []).controller('NavBarCtrl', function NavBarCtrl($scope,$modal,$time

我有以下代码。它每隔几分钟检查一个轮询服务器的工厂。它工作正常,但我想在打开模式时暂停“FetchDataContinous”方法,并在关闭模式时恢复该方法。简而言之,我需要找到一种方法,在打开和关闭modals时切换“fetchDataContinously”。如果我的问题不清楚,请提供建议或让我知道

    angular.module('NavBar', []).controller('NavBarCtrl', function NavBarCtrl($scope,$modal,$timeout,MyPollingService) {

    var ctrl = this;
    fetchDataContinously ();

    function fetchDataContinously () {
        MyPollingService.poll().then(function(data) {


        if(data.response[0].messages[0].important_popup){
          ctrl.showImportantNotice(data.response[0].messages[0]);
          return;
        }
        $timeout(fetchDataContinously, 3000);
        });
    }
    ctrl.showNotices = function () {
        var noticesModalOptions = {
            templateUrl: "notices.html",
            controller: "NoticesCtrl",
            controllerAs: "ctrl",
            show: true,
            scope: $scope,
            resolve: {
                notices: function(NoticesFactory) {
                    return NoticesFactory.getMessages();
                }
            }
        }

      var myNoticesModal = $modal(noticesModalOptions);
      myNoticesModal.$promise.then(myNoticesModal.show);
    }

   ctrl.showImportantNotice = function (importantNotice) {
    ctrl.importantNotice = importantNotice; 
    var importantNoticeModalOptions = {
        templateUrl: "/importantNotice.html",
        controller: "ImportantNoticeCtrl",
        controllerAs: "ctrl",
        show: true,
        scope: $scope,
        onHide: function() {
            console.log("Close !");
            fetchDataContinously();
        },
        onShow: function() {
            console.log("Open !");
        }
    }

  var myImportantNoticeModal = $modal(importantNoticeModalOptions);
  myImportantNoticeModal.$promise.then(myImportantNoticeModal.show);
}

})

在函数中包装您的
$timeout
,并返回它的承诺

var timer;
function startPolling(){
   return $timeout(pollData, 3000);
}
// start it up
timer = startPolling();
取消:

$timeout.cancel(timer);
然后重新开始:

timer = startPolling();

对,所以,当modal打开时,取消超时,然后当它关闭时,重新启动它。我想这就是我迷失的地方。如何从FetchDataContinousy函数外部取消$timeout。。。。例如,我如何在importantNoticeModalOptions.onhide中执行此操作我甚至看不到在代码中调用$timeout
$timeout
返回承诺。记住这一点,如果您想取消,请调用
$timeout.cancel(promise)
。这一切都在…@charlietfl超时时间到了。我还将检查文档。