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

1

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

Fiddle: link

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(); };
}
    
asked by anonymous 14.09.2016 / 14:40

1 answer

0

Ricardo, if you use ui-router in your project. Take a look at Nested States and Views.

With it you can create an abstract state and create other child states by inheriting the $ scope and resolves. I think that's the best way.

link

    
14.09.2016 / 15:16