Skip to content Skip to sidebar Skip to footer

Having An Angular $interval Running Independent Of Controller

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 fun

Solution 1:

Don't bother adding it to $rootScope. Use a service that can be used anywhere in the app. Here is a singleton timer that can start and stop. Define the intervalTimeout in the service itself, or if you want to be really flexible, do so in a provider (probably overkill for this example).

angular.module('myApp', [])

.service('AppCallback', function ($interval) {
    var states = states = {
        PENDING: 0,
        STARTED: 1
    }, intervalTimeout = 3000, // Set this
    interval;

    this.states = states;
  
    this.state = states.PENDING;
    this.start = function (callback) {
        if (this.state !== states.PENDING) {
            return;
        }

        interval = $interval(callback, intervalTimeout);
        this.state = states.STARTED;
    }

    this.stop = function () {
        if (this.state !== states.STARTED) {
            return;
        }
        $interval.cancel(interval);
        this.state = states.PENDING;
    };
})

.controller('MainController', function ($scope, AppCallback) {
  var vm = {},
      count = 0;
  
  vm.toggle = functiontoggle() {
    if (AppCallback.state === AppCallback.states.PENDING) {
      AppCallback.start(function () {
        vm.data = 'Ticked ' + (++count) + ' times.';
      });
     } else {
       AppCallback.stop();
     }
  };
  
  
  $scope.vm = vm;
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="myApp"ng-controller="MainController">
  {{vm.data}}
  <br /><buttonng-click="vm.toggle()">Toggle</button></div>

Solution 2:

If you want to share any data between controllers the correct way is to use a service.

I would then create a service that allows you to stop and start this timer / interval.

The initial controller would kick this off and it would continue to "tick" forever until it is stopped.

Post a Comment for "Having An Angular $interval Running Independent Of Controller"