AngularJS $rootscope 上的 $destroy 永远不会被调用来取消超时

AngularJS $destroy on $rootscope never gets called to cancel timeouts

我有以下代码-

function initialize() {
  var defer = $q.defer();
  var deferTimer = $q.defer();

  var cancelTimeout = $timeout(function() {
    if (defer !== null) {
      ctrlr.setProcessingParameters('XXX');
      defer = ctrlr.openProgressBar();
      deferTimer.resolve();
    }
  }, 1000);

  deferTimer.promise.then(function() {
    var cancelTimeout2 = $timeout(function() {
      if (defer !== null) {
        defer.resolve();
        ctrlr.setProcessingParameters('Please Wait...');
        defer = ctrlr.openProgressBar();
      }
    }, 4000);
  });

  //Process Backend service n resolbve defer....

}

// cancel the $timeout service
$rootScope.$on('$destroy', function() {
  logger.log("cancelTimeout..timer..");
  if (cancelTimeout) {
    $timeout.cancel(cancelTimeoutProcess);
    cancelTimeout = null;
  }
});

// cancel the $timeout service
$rootScope.$on('$destroy', function() {
  logger.log("cancelTimeout2..timer..")
  if (cancelTimeout2) {
    $timeout.cancel(cancelTimeout2);
    cancelTimeout2 = null;
  }
});

我没有看到记录器打印或调试器进入 $destroy。不确定这里发生了什么。

$rootScope 在您关闭或离开页面时被销毁。那时一切都会消失,所以那时没有什么可清理的。

您要找的是 $destroy $scope 而不是

$scope.$on('$destroy', function() {
  logger.log("cancelTimeout..timer..");
  if (cancelTimeout) {
    $timeout.cancel(cancelTimeoutProcess);
    cancelTimeout = null;
  }
});

在控制器中,当与当前 $scope 关联的控制器(而不是整个应用程序)被销毁时,将调用 $scope.$on('$destroy'..