gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:20:51 26 4
gpt4 key购买 nike

Angular,UI 路由器。在像这样的状态 Controller 中使用 $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);
}
};

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

我猜因为间隔和超时是 services在 angular 中,它们随处可用,但我仍然不明白它们如何看待未初始化 Controller 中的函数,除非它被复制。我的解决方案是只使用常规的旧 js 间隔吗?

最佳答案

清除间隔 $destroy

像这样

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

关于angularjs - 如何在离开 ui-state 时停止 $interval?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30938963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com