Reputation: 35286
I have a countdown directive that is counting down from the initial value that's in the element to 0 once a modal warns the user their session is about to timeout. Once the countdown reaches zero the user is prompted with a modal to either exit, or continue. If they hit continue, eventually if they get that same session expiration warning modal, the counter is then 0. I can't quite figure out how to reset the counter directive without just returning it and stopping it on all future warnings. Here's the code I have now.
.directive("ndCountdown", function($timeout, $compile){
return{
restrict: 'A',
link: function(scope, element, attrs){
var countdown = function(){
var timer = element.find('strong');
for(var i = 0; i < timer.length; i++){
var secs = parseInt(timer.text(), 10) - 1;
if(secs >= 0){
timer.text(secs);
} else{
//reset the element to the original value
//stop the timeout in this session but have it continue to
//work in future dialogs.
}
}
$timeout(countdown, 1000);
}
countdown();
}
}
});
Upvotes: 0
Views: 656
Reputation: 8427
First step would be to save the variable of what is inside originally. Then only run the timeout if you are not at the end.
.directive("ndCountdown", function($timeout, $compile){
return{
restrict: 'A',
link: function(scope, element, attrs){
var timer = element.find('strong'),
MAX = parseInt(timer.text());
var countdown = function(){
for(var i = 0; i < timer.length; i++){
var secs = parseInt(timer.text(), 10) - 1;
if(secs >= 0){
timer.text(secs);
$timeout(countdown, 1000);
} else{
timer.text(MAX);
}
}
}
countdown();
}
}
});
Now if you needed to be able to restart it, you would probably want to communicate something from your controller. Maybe a $broadcast like this. be sure to inject $rootScope
$rootScope.$broadcast('event:start-countdown');
Then in your directive you add this at the end of your link function, and inject $rootScope. again.
$rootScope.$on('event:start-countdown', function() {
countdown();
}
Upvotes: 1