如何在离开 ui-state 时停止 $interval? [英] How to stop $interval on leaving ui-state?

查看:26
本文介绍了如何在离开 ui-state 时停止 $interval?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angular,UI 路由器.在像这样的状态控制器中使用 $interval :

Angular, UI-router. Using $interval in a controller of a state like so:

$scope.Timer = null;

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

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

问题?计时器在离开状态时仍然存在.我的理解是 $scope 和控制器在离开状态时基本上被破坏"了.因此,基于此,计时器应该停止(在控制器内,我在四处移动时取消计时器,这是有效的 - 但如果我导航到差异状态,它仍然存在).我在这里误解了什么?

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. 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?

我猜因为间隔和超时是角度的服务,所以它们是可用的无处不在,但我仍然不明白他们如何看待未初始化控制器中的函数,除非它被复制.我的解决方案是只使用常规的旧 js 间隔吗?

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?

推荐答案

上的清除间隔$destroy

像这样

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

这篇关于如何在离开 ui-state 时停止 $interval?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆