如何在退出ui状态时停止$ interval? [英] How to stop $interval on leaving ui-state?

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

问题描述

有角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和控制器实际上被破坏"了.因此,基于此,计时器应该停止(在控制器内,我在移动时取消了计时器,该计时器可以工作-但是如果我导航到diff状态,该计时器仍然存在).我在这里误会什么?

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状态时停止$ interval?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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