Poot87 Poot87 - 5 months ago 27
AngularJS Question

How do I cancel $interval only on leaving a state in AngularJS?

The idea is for a modal to open on a specific page after the user has been on it for 10 seconds, and cancel it if the user leaves the page. It works when I refresh the page, but when I navigate to the page my code cancels the $interval when it is loaded.

In my controller:

$rootScope.$on("$locationChangeStart", function(event, next, current) {
$interval.cancel(interval);
});

$scope.openmodal = function () {
interval = $interval(function () {
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: 'modal.html',
controller: 'ModalInstanceCtrl',
size: 'lg',
});
}, 10000, [1]);
}

$scope.openmodal();


The problem is the the $locationChangeStart is executed when the state is loaded coming from a different state. When I just refresh the browser the $locationChangeStart doesn't run and the modal will open after 10 seconds. How do I stop my controller from calling the $interval.cancel() method when loading from a different state?

Answer
$scope.$on('$stateChangeSuccess', function() { 
    $interval.cancel(interval);
});

Please read ui-router's docs specifically the events section.

Comments