Best way to inherit a controller and override an angularjs 1.5.x routine


Below is my code that implements inheritance using $controller. Is this way okay? My goal is to reuse a baseController class that will have some common routines for crud controllers.


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

myApp.controller('parentController', parentController);
function parentController() {
    var vm = this;
    vm.mainRoutine = mainRoutine;
    vm.subRoutine = subRoutine;

    //1: use the vm before call subRoutine, just solved the future override
    function mainRoutine() { return vm.subRoutine(); };
    function subRoutine() { return 'parent'; };

myApp.controller('child1Controller', child1Controller);
child1Controller.$inject = ['$controller'];
function child1Controller($controller) {
    var vm = this;
    var base = $controller('parentController');
    angular.extend(vm, base);

    //2: override  
    base.subRoutine = subRoutine;
    vm.childRoutine = childRoutine;
    vm.callParentRoutine = callParentRoutine;

    function subRoutine() { return vm.subRoutine() + ' -> child1'; };
    function childRoutine() { return 'childRoutine'; };
    function callParentRoutine() { return vm.mainRoutine(); };


Ricardo, in case you are going to use ui-router in your project. Take a look at Nested States and Views.

With it you can create an abstract state(route) and create other child states inheriting the $scope and resolves. I believe this is the best way.

Scroll to Top