Pet Day Care (Services)

Example of code reuse through services

by rajeshpillai

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 service for dog wakling</span>

<div ng-controller="DogListCtrl">
    <h3>Dogs</h3>
    <table class="table">
        <tr>
            <th>Breed</th>
            <th>Name</th>
            <th></th>
        </tr>
        <tr ng-repeat="pet in pets | orderBy:sorter.sortField">
            <td>{{pet.breed}}</td>
            <td>{{pet.name}}</td>
            <td><a href="" ng-click="walk(pet)">walk</a>
            </td>
        </tr>
    </table>
    <ul class="list-unstyled">
        <li ng-repeat="log in logs track by $index">{{log}}</li>
    </ul>
</div>
</div>

JavaScript

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()
    };
});

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

// List of Dogs. Supports walking.
function DogListCtrl($scope, dogwalk) {
    $scope.logs = [];

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

    // Walk the dog with the dogwalk service.
    $scope.walk = function (pet) {
        this.logs.push(dogwalk(pet.name))
    }
}