<h1>Example: Shared Service</h1>
<p>factoryを使って値を共有、$watchを使って値の変更を監視する。</p>
<div ng-app="myApp">
  <div ng-controller="mainController as main" class="ctrl">
    <h2>mainController</h2>
    <p>{{ main.count }}</p>
    
    <div ng-controller="firstController as first" class="ctrl left">
      <h3>firstController</h3>
      <p>$emitは自身と親のコントローラーにイベントを伝達する。</p>
      <p>{{ first.count }}</p>
      <button ng-click="first.countUp()">CountUp</button>
    </div>

    <div ng-controller="secondController as second" class="ctrl right">
      <h3>secondController</h3>
      <p>$broadcastは自身と子のコントローラーにイベントを伝達する。</p>
      <p>{{ second.count }}</p>
      <button ng-click="second.countUp()">CountUp</button>
    </div>
   </div>
</div>
@import "bourbon";

body {
  padding: 1.5rem;
  
  font-size: .8em;
}

.ctrl {
  @include clearfix();
  padding: .5rem;
  border: 1px solid #aaa;
  box-sizing: border-box;
  
  &.left {
    float: left;
    width: 50%;
  }
  
  &.right {
    float: right;
    width: 50%;
  }
}
View Compiled
(function() {
  "use strict";

  var appName = 'myApp';

  angular
    .module(appName, []);

  angular
    .module(appName)
  	.factory('SharedStateService', SharedStateService)
    .controller('mainController', mainCtrl)
    .controller('firstController', firstCtrl)
    .controller('secondController', secondCtrl);

  // Shared Service
  function SharedStateService(){
    return {
      count: 0
    }
  }
  
  function mainCtrl($scope, SharedStateService){
    var vm = this;

    vm.count = SharedStateService.count;
    
    $scope.$watch(function(){
      return SharedStateService.count;
    }, function(){
      vm.count = SharedStateService.count;
    });

  }

  function firstCtrl($scope, SharedStateService){
    var vm = this;

    vm.countUp = countUp;
    vm.count = SharedStateService.count;
    
    $scope.$watch(function(){
      return SharedStateService.count;
    }, function(){
      vm.count = SharedStateService.count;
    });

    function countUp(){
      SharedStateService.count++;
    }
  }

  function secondCtrl($scope, SharedStateService){
    var vm = this;

    vm.countUp = countUp;
    vm.count = SharedStateService.count;
    
    //watchを使った変更の監視
    $scope.$watch(function(){
      return SharedStateService.count; //監視する値
    }, function(){
      vm.count = SharedStateService.count;
    });

    function countUp(){
      SharedStateService.count++;
    }
  }

})();

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js