Sharing is Caring

by Rob Rothe

HTML

<div ng-app="app">
  <h4>
  Controller 1
  </h4>
  <div ng-controller="Controller1 as ctrl">
    Item: {{ctrl.item}}
  </div>
  <hr>
  <h4>
  Controller2
  </h4>
  <div ng-controller="Controller2 as ctrl">
    Item: {{ctrl.item}}
    <br>
    <button ng-click="ctrl.updateItem()">
      Update
    </button>
  </div>
</div>

JavaScript

angular
  .module('app', [])
  .controller('Controller1', Controller1)
  .controller('Controller2', Controller2)
  .factory('Service', Service);

function Controller1(Service) {
  var vm = this;
  vm.item = Service.item;
}

function Controller2(Service) {
  var vm = this;
  vm.item = Service.item;
  vm.updateItem = updateItem;

  function updateItem() {
    vm.item = 'New';
  }
}

function Service() {
  var service = {
    item: 'Current'
  };

  return service;
}