简体   繁体   中英

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

I have the following code -

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;
  }
});

I do not see the loggers print or debugger gets into $destroy . Not sure what's happening here.

$rootScope gets destroyed when you close or leave the page. Everything will be gone then, so there's nothing to clean up at that time.

What you are looking for is $destroy on $scope instead,

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

While in the controller, $scope.$on('$destroy'.. will be called when controller gets destroyed (and not the whole application) with which current $scope is associated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM