AngularJS $ is applied is not called in the interval when the $ variable has changed from one controller to another and back
I am creating this directive with Angular that works like a mini timer. I don't need anything more than just counting seconds and minutes. The directive works fine as long as I stay on the page where the directive is called.
The problem is when I switch to another page and then come back, I need a timer to be displayed with the current time.
I have a global object window.timer
that stores the state of the timer.
app.directive('callTimer', function() {
return {
restrict: 'E',
controller: function($scope, $rootScope) {
$scope.minutes = (window.timer.state.minutes || 0)
$scope.seconds = (window.timer.state.seconds || 0)
$scope.startTimer = function() {
window.timer.interval = window.setInterval(function() {
// incrementTimer
window.timer.state = {minutes: $scope.minutes,seconds: $scope.seconds};
$scope.$apply($scope.updateDisplay);
}, 1000);
};
$scope.stopTimer = function() { /*stuff to stop timer*/};
$scope.updateDisplay = function() {
$scope.minDisplay = String($scope.minutes).padLeft('0', 2);
$scope.secDisplay = String($scope.seconds).padLeft('0', 2);
};
$scope.updateDisplay();
}
};
});
Here is the html
<call-timer>{{minDisplay}}:{{secDisplay}}</call-timer>
The timer is on my home page. When I go to another page, the timer will keep counting down, but when I return to the home page, my function updateDisplay
will not be called.
EDIT: Adding more directive code.
source to share
Ok so I figured it out. The problem is that the $ scope inside the interval is actually a different controller instance than the outer one, after you've gone from one controller to another and back again. Here is my code (it's really in coffeescript).
It's not the prettiest, but the idea is to convey the area I want to use when I update the view. If anyone has any idea on how I can clean this up, that would be awesome, but this code does exactly what I need it to do.
source to share