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

VSO*_*VSO 13 intervals angularjs angular-ui-router

Angular,UI路由器.在如下状态的控制器中使用$ 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);
    }
};
Run Code Online (Sandbox Code Playgroud)

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

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

Ani*_*bhi 26

清除间隔 $destroy

像这样

$scope.$on("$destroy",function(){
    if (angular.isDefined($scope.Timer)) {
        $interval.cancel($scope.Timer);
    }
});
Run Code Online (Sandbox Code Playgroud)