title: Having an Angular $interval running independent of controller
body: <p>I have different pages on may application which have their own controllers. One of them has an $interval function, let's say a timer. Click on a button will start this interval function, which updates itself every second. What i want to have is, i want to be able to <strong>go to any other page</strong> in my application (calling different controllers), but <strong>i want my interval to continue running</strong> until i stop it explicitly from the first controller. A <em>rootScope interval</em> so to speak. How can i do it?</p>
  
  <p>EDIT: Thanks to Chris and Patrick i now have a simple Service, looks like this:</p>
  
  <pre><code>  .service('TimerService', function($interval) {
      var promise;
      var timerSeconds = 0;
  
      this.start = function () {
        promise = $interval(function () {
          timerSeconds++;
        }, 1000);
      };
  
      this.stop = function () {
        promise.cancel(interval);
        timerSeconds = 0;
      };
  
      this.getTimer = function() {
        return timerSeconds;
      }
    })
  </code></pre>
  
  <p>I store also my current value (timerSeconds) in this service. But how can i sync this value to my controller? The service increments the timerSeconds, and at the beginning of my controller i read it from this service through its getTimer() function, but it clearly will not be updated on my controller. <strong>How can i sync this service attribute with my local attribute?</strong></p>
  
  <p>EDIT:</p>
  
  <p>when i define my service attribute as an object and the timerSeconds as number inside that object (it seems primitives cannot be synced):</p>
  
  <pre><code>var timer = {seconds : 0};
  
  this.getTimer = function() {
    return timer;
  }
  </code></pre>
  
  <p>and get this object from my controller through that getter:</p>
  
  <pre><code>vm.timer = TimerService.getTimer();
  </code></pre>
  
  <p>they are all in sync.</p>