Reputation: 105
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?
Upvotes: 0
Views: 994
Reputation: 2569
$scope.$on('$stateChangeSuccess', function() {
$interval.cancel(interval);
});
Please read ui-router
's docs specifically the events section.
Upvotes: 1
Reputation: 566
You need to start the timer each time a new state is loaded in the controller of the state. If user remains on the state , the modal will be displayed. But if user leaves the state before opening the modal you need to cancel the timer as the new state will again be initiating a new instance of the timer.
$scope.$on('$destroy', function() {
$interval.cancel(interval);
});
var interval = $interval(function () {
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: 'modal.html',
controller: 'ModalInstanceCtrl',
size: 'lg',
});
}, 10000, [1]);
Upvotes: 0