AngularJS - A Better Way to Implement a Base Controller

There's quite a few different ways of implementing a base controller in AngularJS that people have posted about. Some use pure JavaScript prototypal inheritance while others do it with angular services/factories, however the cleanest and simplest way I've found is to use the AngularJS $controller service. 

Here's a cut down example from an application I'm working on at the moment, it contains controllers for adding and editing diary entries, and a base controller containing shared functionality.

'use strict';


// base controller containing common functions for add/edit controllers
    ['$scope', 'DiaryService',
    function ($scope, DiaryService) {
        $scope.diaryEntry = {};

        $scope.saveDiaryEntry = function () {

        // add any other shared functionality here.

    ['$scope', '$controller',
    function ($scope, $controller) {
        // instantiate base controller
        $controller('Diary.BaseAddEditController', { $scope: $scope });

    ['$scope', '$routeParams', 'DiaryService', '$controller',
    function ($scope, $routeParams, DiaryService, $controller) {
        // instantiate base controller
        $controller('Diary.BaseAddEditController', { $scope: $scope });

        DiaryService.GetDiaryEntry($ (data) {
            $scope.diaryEntry = data;

(See working on plunker at

It works by creating an instance of the base controller and injecting it with the child controller's $scope, making all the methods and properties added to the $scope by the base controller available in the child controller as well as the view. Although not technically inheritance in the 'classical programming' sense, it solves the issue of having duplicate code between controllers and quite elegantly in my opinion.

By Jason Watmore


blog comments powered by Disqus