AngularJS Controller Inheritance
AngularJS Controller Inheritance using mixins
Source:http://digital-drive.com/?p=188
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.0/angular.js"></script>
<div id='container' ng-app='ControllerMixins'>
<h2 class="text-center">AngularJS Controller Mixins</h2>
<section ng-controller="DogController as dog" class="text-center">
<p>Dog</p>
<!-- Scope property mixed in, displays: 'color: solid black' -->
<p ng-bind-template="color: {{ dog.color }}"></p>
<!-- Calls an instance method mixed in, outputs: 'BARK BARK!' -->
<button class="btn" ng-click="dog.bark()">Bark Dog</button>
<!-- Scope method mixed in, outputs: 'run speed: 35mph' -->
<button class="btn" ng-click="dog.run()">Run Dog</button>
<button class="btn" ng-click="dog.move()">Move Dog</button>
<br /> <em>open log console to see button click output</em>
</section>
<hr/>
<!-- Similar to Dog, but now for Cat-->
<section ng-controller="CatController" class="text-center">
<p>Cat</p>
<p ng-bind-template="color: {{ color }}"></p>
<button class="btn" ng-click="meow()">Meow Cat</button>
<button class="btn" ng-click="run()">Run Cat</button>
</section>
</div>
CSS
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
JavaScript
/** Base controller **/
function AnimalController($scope, vocalization, color, runSpeed) {
var _this = this;
var _test;
// instance variables
angular.extend($scope, {
_speed: 0,
_position: 0,
_vocalization: vocalization,
_runSpeed: runSpeed,
_color: color
});
angular.extend($scope, {
get test(){
return _ttst
},
set test(value){},
});
// methods
angular.extend($scope, {
vocalize: function(){
console.log($scope._vocalization);
},
run: function(){
console.log("run speed; " + $scope._runSpeed);
$scope._position += $scope._speed;
}
});
}
function DogController($scope) {
var _this = this;
this.scope = $scope;
// Mixin Animal functionality into Dog.
angular.extend(this, new AnimalController($scope, 'BARK BARK!', 'solid black','35mph'));
angular.extend($scope, {
bark: function(){
_this.scope.vocalize();
},
move: function(){
$scope._speed = 10;
$scope.run();
console.log($scope._position);
}
});
}
function CatController($scope) {
var _this = this;
// Mixin Animal functionality into Cat.
angular.extend(this, new AnimalController($scope, 'meeeeeoow!', 'orange', '25mph'));
$scope.meow = function () {
_this.vocalize(); // inherited from mixin.
}
}
angular.module('ControllerMixins', []);