AngularJs 1.5 controllers inheritance

In the first place there is a good style guide for Angular.

When you need to reuse the code of some controller and use controllerAs syntax, you can use inheritance with the call() method.

(function () {

    'use strict';

    angular.module('app.controllers').controller('ChildController1', ChildController1);
    angular.module('app.controllers').controller('ChildController2', ChildController2);

    ChildController1.$inject = ['$scope', '$sce'];
    ChildController2.$inject = ['$scope', '$sce'];

    function ChildController1($scope, $sce) {
        BaseController.call(this, $scope, $sce, 'Title 1');
    }

    function ChildController2($scope, $sce) {
        BaseController.call(this, $scope, $sce, 'Title 2');
    }

    function BaseController($scope, $sce, title) {
        var vm = this;
        vm.title = title;
        vm.sendMessage = function() { };
    }

})();
comments powered by Disqus