Angular Controller Inheritance

by rtcherry

HTML

<script src="http://code.jquery.com/jquery-1.6.4.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<div ng-controller="Child">
    <p><strong>Parent</strong>: {{parent}}</p>
    <p><strong>Parent Method</strong>: {{parentMethod()}}</p>
    <p><strong>Child</strong>: {{child}}</p>
    <p><strong>Child Method</strong>: {{childMethod()}}</p>
    <p><strong>Override Method</strong>: {{overrideMethod()}}</p>
</div>

JavaScript

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

testApp.controller('Parent', ['$scope', '$log', function($scope, $log) {
    $scope.parent = "Parent value!";
    
    $scope.parentMethod = function() {
        $log.info('Parent::parentMethod()');
        return "Parent method!";
    };
    
    $scope.overrideMethod = function() {
        $log.info('Parent::overrideMethod()');
        return "In the parent!";
    };
}]);

testApp.controller('Child', ['$scope', '$controller', function($scope, $controller) {
    $controller('Parent', {"$scope": $scope});
    var $super = angular.extend({}, $scope);

    $scope.child = "Child value!";
    
    $scope.childMethod = function() {
        return "Child method!";
    };
    
    $scope.overrideMethod = function() {
        return "In the child! -> " + $super.overrideMethod();
    };
}]);

angular.element(document).ready(function () {
    angular.bootstrap(document, ['testApp']);
});