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);
}
};
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?
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?
clear interval on $destroy
Like this
$scope.$on("$destroy",function(){
if (angular.isDefined($scope.Timer)) {
$interval.cancel($scope.Timer);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With