Poot87 Poot87 - 1 year ago 124
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) {

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


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 Source
$scope.$on('$stateChangeSuccess', function() { 

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download