简体   繁体   English

如何在离开ui-state时停止$ interval?

[英]How to stop $interval on leaving ui-state?

Angular, UI-router. Angular,UI路由器。 Using $interval in a controller of a state like so: 在如下状态的控制器中使用$ interval:

$scope.Timer = null;

$scope.startTimer = function () { 
    $scope.Timer = $interval($scope.Foo, 30000);
};

$scope.stopTimer = function () {
    if (angular.isDefined($scope.Timer)) {
        $interval.cancel($scope.Timer);
    }
};

The problem? 问题? The timer persists upon leaving the state. 计时器在离开状态时仍然存在。 My understanding was that the $scope and the controller are essentially "destroyed" when a state is left. 我的理解是,当一个州离开时,$ scope和控制器基本上被“摧毁”了。 So, based on that, the timer should stop (Within the controller, I am cancelling the timer when moving around, that works - but it persists if I navigate to a diff state). 因此,基于此,计时器应该停止(在控制器内,我在移动时取消计时器,这是有效的 - 但如果我导航到差异状态它会持续存在)。 What am I misunderstanding here? 我在这里误解了什么?

I guess since interval and timeout are services in angular, they are available everywhere, but I still don't understand how they see functions in the not-initialized controller, unless it's copied. 我猜因为间隔和超时是有角度的服务 ,它们随处可用,但我仍然不明白他们如何在未初始化的控制器中看到函数,除非它被复制。 Is my solution to just use regular good-old js interval? 我的解决方案只是使用常规的良好的旧js间隔?

clear interval on $destroy 清除$destroy间隔

Like this 像这样

$scope.$on("$destroy",function(){
    if (angular.isDefined($scope.Timer)) {
        $interval.cancel($scope.Timer);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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