Pets Day Care (helper controllers)

Example of code organization using composition of helper controllers

by jwstott

HTML

<script src="http://code.angularjs.org/1.2.8/angular.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<div class="container" ng-app>
<h2>Pet Day Care</h2>
<span class="text-muted lead">Using helper controllers</span>

<div ng-controller="DogListCtrl">
  <h3>Dogs</h3>
  <table class="table">
    <tr>
      <th>Type</th>
      <th>Name</th>
      <th></th>
    </tr>
    <tr ng-repeat="pet in pets | orderBy:sorter.sortField">
      <td>{{pet.type}}</td>
      <td>{{pet.name}}</td>
      <td>
        <a href="" ng-click="walkerMgr.walk(pet)">walk</a>
        <span ng-if="!walkerMgr.wasWalked(pet)">
          (Not walked yet)</span>
       </td>
      </tr>
    </table>
    <ul class="list-unstyled">
      <li ng-repeat="walk in walkerMgr.logs track by $index">
        {{walk}}</li>
    </ul>
</div>
</div>

JavaScript

// Basic pet object.
function Pet(name, type) {
    this.name = name;
    this.type = type;
}

var app = angular.module('myApp', []);

// Service that walks a dog.
app.service('dogwalk', function () {
    return function(name) {
        var now = new Date();
        return "Walking " + name + ' at ' +
            now.getHours() + ":" + now.getMinutes() + ':' +
            now.getSeconds()
    };
});

// Object that managers walking a pet.
// This depends on the dog walking service.
function PetWalkingMgr(dogwalk) {
    this.logs = [];
    this.status = {};

    this.walk = function(dog) {
        this.logs.push(dogwalk(dog.name));
        this.status[dog.name] = true;
    }

    this.wasWalked = function(dog) {
        return this.status[dog.name];
    }
};

// List of Dogs. With Dogs we care about the type of dog.
function DogListCtrl($controller, $scope) {
    // Create a helper controller.
    $scope.walkerMgr = $controller(PetWalkingMgr);

    // Create some dogs.
    $scope.pets = [
      new Pet('Pinky', 'Poodle'),
      new Pet('Apples', 'Poodle'),
      new Pet('Killer', 'German Shepard')
    ]
}