Angular Controller inheritance
Example of using controller inheritance.
by yoorek
HTML
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
<div class="container" ng-app>
<h2>Pet Day Care</h2>
<span class="text-muted lead">Using inheritance</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;
}
// The generic pet list controller that contains sorting.
function PetListCtrl($scope) {
$scope.sort = this.sort;
}
PetListCtrl.prototype.sort = function(sortField) {
this.sortField = sortField;
}
// CatList inherits from PetList.
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);
// DogList also inherits from PetList.
function DogListCtrl($injector, $scope) {
$injector.invoke(PetListCtrl, this, {$scope: $scope});
// Create some dogs, including their breed.
$scope.pets = [
new Pet('Pinky', 'Poodle'),
new Pet('Apples', 'Poodle'),
new Pet('Killer', 'German Shepard')
]
}
DogListCtrl.prototype = Object.create(PetListCtrl.prototype);