Service/Controllers

by Rob Rothe

HTML

<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<div ng-app="app" class="container">
  <div ng-controller="Controller1 as ctrl">
    <h1>
   Controller 1
   </h1>
    <ul>
      <li ng-repeat="data in ctrl.data">{{data.item}}</li>
    </ul>
  </div>
  <hr>
  <div ng-controller="Controller2 as ctrl">
    <h1>
   Controller 2
   </h1>
    <ul>
      <li ng-repeat="data in ctrl.data">{{data.item}}</li>
    </ul>
    <hr>
    <ul>
      <li ng-repeat="user in ctrl.users">{{user.name}}</li>
    </ul>
  </div>
</div>

CSS

body {
  padding-top: 20px;
}

JavaScript

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

function Service($http) {
  var service = {
    method1: method1,
    method2: method2
  };

  return service;

  function method1() {
    return [{
      id: 1,
      item: 'Guitar'
    }, {
      id: 2,
      item: 'Bass'
    }];
  }

  function method2() {
    return [{
      id: 1,
      name: 'Jimmy'
    }, {
      id: 2,
      name: 'Robert'
    }];
  }
}

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

function Controller2(Service) {
  var vm = this;
  vm.data = Service.method1();
  vm.users = Service.method2();
}