Angular mixins

Example of using controller inheritance and mixins.

by yoorek

HTML

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
<div ng-app>
    <h2>Pet Day Care</h2>
    <span class="text-muted lead">Using mixins for sorting</span>

    <div ng-controller="CatListCtrl">
        <h3>Cats</h3>
        <span data-ng-if="sortField">Sorting by {{sortField}}
        </span>
        <table class="table">
            <tr>
                <th class="sortable" ng-click="sort('name')">Name</th>
            </tr>
            <tr ng-repeat="pet in pets | orderBy:sortField">
                <td>{{pet.name}}</td>
            </tr>
        </table>
    </div>
    
    <hr/>
 
    <div ng-controller="DogListCtrl">
        <h3>Dogs</h3>
        <span data-ng-if="sortField">Sorting by {{sortField}}
        </span>
        <table class="table">
            <tr>
                <th class="sortable" ng-click="sort('breed')">Breed</th>
                <th class="sortable" ng-click="sort('name')">Name</th>
            </tr>
            <tr ng-repeat="pet in pets | orderBy:sortField">
                <td>{{pet.breed}}</td>
                <td>{{pet.name}}</td>
            </tr>
        </table>
    </div>
</div>

CSS

th.sortable {
    cursor: pointer;
}

th.sortable:hover {
    background-color: #ddd;
}

JavaScript

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

// Mixin for sorting.
function SortMixin() {
    this.sort = function(sortField) {
        this.sortField = sortField;
    };
}

// The generic list controller that mixes in sorting.
function PetListCtrl($scope) {
    this.$scope = $scope;
    
    // Add sort mixin's function to the $scope.
    // Sort functions will now be directly accessible in the UI.
    angular.extend($scope, new SortMixin())
}

function CatListCtrl($injector, $scope) {
    $injector.invoke(PetListCtrl, this, {$scope: $scope});

    $scope.pets = [
        new Pet('General Snuggles'),
        new Pet('Mittens'), 
        new Pet('Fluffyface')
    ]
}
CatListCtrl.prototype = Object.create(PetListCtrl.prototype);

function DogListCtrl($injector, $scope) {
    $injector.invoke(PetListCtrl, this, {$scope: $scope});

    $scope.pets = [
        new Pet('Pinky', 'Poodle'),
        new Pet('Apples', 'Poodle'),
        new Pet('Killer', 'German Shepard')
    ]
}
DogListCtrl.prototype = Object.create(PetListCtrl.prototype);