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.

+3


source to share


2 answers


| Is this a single page application? If so, don't store the timer in the directive. Store it on some controller or somewhere else. Reserves are recreated when navigating to another page, so there is no way to store the timer value in the directive.



0


source


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.



https://gist.github.com/jwoertink/5256e80f393a150f8b21

0


source







All Articles