0

With the help of user3696882 I managed to set up a service:

app.service('metro', function() {
    this.flagValue = {value: false};
    this.setFlagValue = function(flagValue){
         this.flagValue.value = flagValue;
    };
    this.getFlagValue = function(){
         return this.flagValue;
    };
  });

that forms the model for a boolean that is being toggled true/false every second by one of my controllers:

function GlobalCtrl( $scope , $interval , metro ) {
  var th = this;

  $interval(function () {

     th.pulse = !th.pulse;

     metro.setFlagValue( th.pulse );

  }, 1000 );

}

The toggling model in my service can show up in another part of the view - accessed by a different controller:

function ViewCtrl( $scope , metro ) {
    var th = this;

    th.pulse =  metro.getFlagValue() ;
}

Full solution available in this Plunker

Maybe I am taking things too far, but I'd like to be able to have a service depending on $interval which toggles its own model.

I made:

app.factory('loop_toggle', ['$interval', function($interval ) {

  var flagObj = {value: false};

  function flip() {
    flagObj.value = !flagObj.value;
  }

  $interval(flip, 1000);

   return  {
    current : flagObj
   };

}]);

However, with my modifed controller:

function ViewCtrl( $scope , metro , loop_toggle ) {
  var th = this;

  th.pulse = metro.getFlagValue() ;

  th.loop = loop_toggle.current.value;
}

I cannot see anything toggling: just a static "false".

Development so far available in this Plunker

I suppose I could make do with a service metronome being toggled by a controller - but isn't that having business logic in the wrong place?

1 Answers1

0

You need to update th.loop after each second,

Add dependaincies into ViewCtrl

ViewCtrl.$inject = ['$scope' , 'metro' , 'loop_toggle',  '$interval' ] ;

Update your th.loop using $interval

function ViewCtrl( $scope , metro , loop_toggle, $interval ) {
  var th = this;

  th.pulse = metro.getFlagValue() ;

  $interval(function () {

     th.loop = loop_toggle.current.value;

  }, 1000 );      
}

Updated plunker

metro service doesn't need $interval, but Why loop_toggle factory needs $interval to update value?

Here are some explanations Service vs Factory

Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48
  • I think I was a bit hazy about what should go in a controller: toggling classes [based on some enumerate value in an attribute in the view - or based on some model in a service] is **view control** (**not** business logic) which is just the sort of thing to have in a controller. On reflection, there is no issue. Many thanks for your answer, tho. – rupertrealbear May 02 '18 at 15:59