<!DOCTYPE html>
<html data-ng-app="testApp">
  <head>
    <script data-require="angular.js@1.3.1" data-semver="1.3.1" src="//code.angularjs.org/1.3.1/angular.js"></script>
  </head>
  <body data-ng-controller="Ctrl">
    Please watch the JavaScript console.<br>
    <button ng-click="buttonclick(false)">updateState(constant)</button>
    <button ng-click="buttonclick(true)">updateState(random)</button>
    <script src="script.js"></script>
  </body>
</html>
var UPDATE_STATE_DELAY = 500;
var CONTROLLER_INIT_DELAY = 1000;
var app = angular.module('testApp', []);


app.factory('StateService', ['$rootScope', '$timeout',
function($rootScope, $timeout) {
  
  console.log('StateService: startup.');
  var service = {state: {data: null}};
  
  service.updateState = function(rnd) {
    console.log("StateService: updateState(). Retrieving data...");
    $timeout(function() {
      console.log("StateService: ...got data, assign it to state.data.");
      if (rnd)
        service.state.data = Math.floor(Math.random()*1000).toString();
      else
        service.state.data = "constantpayload";
    }, UPDATE_STATE_DELAY);
  };

  // Update state automatically once upon service (app) startup.
  service.updateState();

  return service;
}]);


app.controller('Ctrl', ['$scope', '$timeout', 'StateService',
function($scope, $timeout, stateService) {
  
  function useStateData() {
    console.log("Ctrl: useStateData(): " + stateService.state.data);
  }
  
  function init() {
    console.log('Ctrl: init. Install watcher for stateService.state.data.');
    $scope.$watch(
      function() {return stateService.state.data;},
      function(newValue, oldValue) {
        console.log("Ctrl: stateService.state.data watcher: triggered.");
        if (newValue !== oldValue) {
          console.log("Ctrl: stateService.state.data watcher: data changed, use data.");
          useStateData();
        }
        else
          console.log("Ctrl: stateService.state.data watcher: data did not change: " + oldValue);
      }
    );    
    
  }
  
  // Simulate longish app init time: delay execution of this controller init.  
  $timeout(function() {
    init();
  }, CONTROLLER_INIT_DELAY);
  
  $scope.buttonclick = function(random) {
    console.log("Ctrl: Call stateService.updateState() due to button click.");
    stateService.updateState(random);
  };
}]);