Software Development

Step-by-Step Guide To Extending A Controller In AngularJS

Extending a controller in AngularJS involves reusing logic through inheritance or composition to share behavior, improve maintainability, and reduce duplicated code across application modules.

calender img Last update date: April 14, 2026

Quick Summary :-

In this guide on Angular JS, we dive deeper into this framework and discuss some tips, tricks, and benefits of AngularJS. Besides discussing in detail the controller function, we have discussed the best way to create the base controller in AngularJS. Dig deeper and know more about it.

AngularJS remains a widely recognized JavaScript framework for building interactive browser-based applications. Its MVC structure, declarative syntax, and tight integration with HTML make it suitable for maintaining complex front-end logic without introducing unnecessary overhead.

For developers working with legacy systems, understanding AngularJS frameworks and the benefits of using AngularJS is still relevant. These capabilities support cleaner code organization, reusable components, and consistent application behavior across views.

front-end development services market

Industry projections show the front-end development services market growing at a 9.50% CAGR, with total market value expected to reach USD 16 billion by 2030, underscoring continued demand for structured front-end expertise and framework-driven development approaches.

Which Steps Are Required to Extend a Controller in AngularJS?

The following steps outline a practical approach to extending AngularJS controllers, helping developers reuse logic, manage scope behavior, and maintain structured application flow effectively.

Tricks With angular.extend()

Before understanding the trick with angular.extend(), you must first understand what exactly it is. For copying object to object, AngularJS has a built-in method called angular.extend(). AngularJS extend controller is considered to be a very powerful function with a plethora of uses.

For your convenience, you can find the documentation for the same here:

https://docs.angularjs.org/api/ng/function/angular.extend

Now you are familiar with the Angular extend controller. It is time to see the tricks. Let us start to understand the tricks with the Angular extend controller by considering a mythical ThingController. It will resemble the use of traditional Angular functions in controllers.

app.controller(‘ThingController’, [ ‘$scope’, function($scope) {
$scope.thingOne = ‘one’;
$scope.thingTwo = ‘two’;
$scope.getThings = function() {
return $scope.thingOne + ‘ ‘ + $scope.thingTwo;
};
}]);

As you are here to learn and we are here to guide, so we are going to make things easier for you to understand. In effect of this, here for explaining, we are going to give lots of assignments to $scope for building member variables and methods. You can refer below code fragment to understand how it will look if we used Angular extend controllers:

app.controller(‘ThingController’, [ ‘$scope’, function($scope) {
angular.extend($scope, {
thingOne: ‘one’,
thingTwo: ‘two’,
getThings: function() {
return $scope.thingOne + ‘ ‘ + $scope.thingTwo;
}
});
}]);

After this code fragment, here is a tip for you. When you want a cleaner way to express all these assignments to $scope, consider making use of the Angular extend controller.

You may find your models and methods mixed up here in some arbitrary order. But the good part is that you can clean it up. How? Get the guidance from the below code fragment:

app.controller(‘ThingController’, [ ‘$scope’, function($scope) {
// models
angular.extend($scope, {
thingOne: ‘one’,
thingTwo: ‘two’
});

// methods
angular.extend($scope, {
// in HTML template, something like {{ getThings() }}
getThings: function() {
return $scope.thingOne + ‘ ‘ + $scope.thingTwo;
}
});
}]);

Do you want application code to store to thingOne and thingTwo only when values are valid? You can utilize getters & setters and apply private variables for holding the applicable values. You can refer to the below code fragment to understand how.
app.controller(‘ThingController’, [ ‘$scope’, function($scope) {
// private
var _thingOne = ‘one’,
_thingTwo = ‘two’;

// models
angular.extend($scope, {
get thingOne() {
return _thingOne;
},
set thingOne(value) {
if (value !== ‘one’ && value !== ‘two’) {
throw new Error(‘Invalid value (‘+value+‘) for thingOne’);
},
get thingTwo() {
return _thingTwo;
},
set thingTwo(value) {
if (value !== ‘two’ && value !== ‘three’) {
throw new Error(‘Invalid value (‘+value+‘) for thingTwo’);
}
});

// methods
angular.extend($scope, {
// in HTML template, something like {{ things }}
get things() {
return _thingOne + ‘ ‘ + _thingTwo;
}
});
}]);

You can also implement mixins by using the Angular extend controller. For this, take the below contrived logging class into consideration:
var debug = true,
Logger = {
print: function(s) {
return debug ? s : ‘’
}
};

After all of this understanding and executing, we have got one more trick for you to use Angular extend controller. You can try “mixin” the below logger class using Angular extend controller to $scope in numerous controllers. Do you want to understand how? Refer below code:

app.controller(‘ControllerOne’, [ ‘$scope’, function($scope) {
// mixin $scope
angular.extend($scope, Logger);
// define our $scope
angular.extend($scope, {
myVar: 1,
log: function() { this.print(this.myVar); }
});
}]);

app.controller(‘ControllerTwo’, [ ‘$scope’, function($scope) {
// mixin $scope
angular.extend($scope, Logger);
// define our $scope
angular.extend($scope, {
myVar: 2,
log: function() { this.print(this.myVar); }
});
}]);

In a view administered by ControllerOne, you will see {{ log() }} rendering “1” into the DOM, which is the value of myVar. In a view managed by ControllerTwo, you will observe {{ log() }} rendering “2” into the DOM. So you see, we defined mixin for just once and used it twice. Likewise, you can use mixin several times by just creating it for once.

If in case, you are changing the debug variable to false, no value insertion in DOM will take place.

Before you go and try implementing an angular extend controller, here are alarm bells. You may find jquery.extend(), jqlite.extend(), and angular extend controller broken. But you can find the bug report filed for angular extend controller by following the below link:

https://github.com/angular/angular.js/issues/8573.

Employee Size

DID YOU KNOW?

Usage data shows Angular adoption is strongest among mid-sized organizations, with the highest concentration of users in companies employing 100 to 249 people, followed by firms with 20 to 49 employees and larger teams exceeding one thousand staff members.

Understanding Controllers In Angularjs

The more things you see in front of your eyes, the more you get confused. And it becomes more struggling with the things having similarity among them. Similar is the case with controllers in AngularJS, hire angularjs developers to solve complex modern problems of developing dynamic web applications

While creating complicated web applications using multiple controllers, you may find more than one controllers performing similar tasks, but may possess slight differences. To solve the problem of code duplication, you can create a base controller in AngularJS. You can extend the behavior of this base controller in other controllers in AngularJS.

To make you practically understand this concept, we have done below work. Go through the codes and steps to understand how this works.

Need Technical Support for AngularJS Architecture?

Work with eSparkBiz to manage controller inheritance and reuse effectively.

Start Your Project

Creating Controllers in AngularJS

Let’s start creating controllers in AngularJS. Here, we are defining two separate controllers in AngularJS – SimpleCalculatorCtrl and AdvancedCalculatorCtrl.
angular
.module("myAwesomeApp", [])

.controller(“SimpleCalculatorCtrl”, function() {
var vm = this;

vm.add = add;
vm.subtract = subtract;

function add(a, b) {
vm.result = a + b;
}

function subtract(a, b) {
vm.result = a – b;
}
});

.controller(“AdvancedCalculatorCtrl”, function() {
var vm = this;

vm.add = add;
vm.subtract = subtract;
vm.multiply = multiply;
vm.divide = divide;

function add(a, b) {
vm.result = a + b;
}

function subtract(a, b) {
vm.result = a – b;
}

function multiply(a,b) {
vm.result = a * b;
}

function divide(a, b) {
vm.result = a / b;
}
});

After this brain work, now we are going to use our new controllers in AngularJS. Here we go.
new controllers in AngularJS

In the above code fragment, you must have seen that AdvancedCalculator and SimpleCalculator both have similar delete and add functions. But AdvancedCalculator has additional multiply and divide functions. If you want to simplify both the controllers in AngularJS, create a CalculatorService. This will watch out the actual logic.

Apart from this, both the controllers in AngularJS, SimpleCalculator and AdvancedCalculator, will also update the result and show the new value on the DOM.

Creating a Base Controller

Now, let us move towards creating a base controller in AngularJS for our calculator controllers. Here, we are going to add the functionalities of both SimpleCalculator and AdvancedCalculator in the base controller in AngularJS.

angular
.module("myAwesomeApp", [])

.controller(“CalculatorCtrl”, function() {
var vm = this;

vm.add = add;
vm.subtract = subtract;

vm.data = {};

function add(a, b) {
vm.data.result = a + b;
}

function subtract(a, b) {
vm.data.result = a – b;
}
});

Extending the Base Controller

You can simplify AdvancedCalculator and SimpleCalculator controllers in AngularJS following the below code:

angular
.module("myAwesomeApp", [])

.controller(“SimpleCalculatorCtrl”, function($scope, $controller) {
var vm = this;

// Inherit from Base Controller
angular.extend(vm, $controller(‘CalculatorCtrl’, {
$scope: $scope
}));
})

.controller(“AdvancedCalculatorCtrl”, function($scope, $controller) {
var vm = this;

// Inherit from Base Controller
angular.extend(vm, $controller(‘CalculatorCtrl’, {
$scope: $scope
}));

vm.multiply = multiply;
vm.divide = divide;

function multiply(a,b) {
vm.data.result = a * b;
}

function divide(a, b) {
vm.data.result = a / b;
}
});

After following the above coding procedure, both the controllers in AngularJS will be free from duplicate codes. This all happened just by extending the base controller in AngularJS, which is CalculatorCtrl.

You can do this by injecting $controller in AngularJS to initialize the base controller. Then you can use Angular extend controller for extending current controller in AngularJS with the base controller.

The result property is moved to the controller in AngularJS into an empty Object, namely data. This is supposed to do because the functionalities of JavaScript doesn’t change the underlying Object itself even after changing the value of a variable.

We would suggest you to implement $controller in AngularJS as it is the simplest way to get your work done. You can also refer to the below example.

This example shows the use of controllers in AngularJS to add and edit diary entries. You will also find in this example a base controller in AngularJS, which contains shared functionality.

What Is the Best Approach for Creating a Base Controller in AngularJS

This approach helps keep common functionality in one place, making applications easier to manage, update, and scale as features grow over time.

A-Better-Way-to-Create-Base-Controller

'use strict';

angular.module(‘Diary’)

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

$scope.saveDiaryEntry = function () {
DiaryService.SaveDiaryEntry($scope.diaryEntry);
};

// add any other shared functionality here.
}])

.controller(‘Diary.AddDiaryController’,
[‘$scope’, ‘$controller’,
function ($scope, $controller) {
// instantiate base controller
$controller(‘Diary.BaseAddEditController’, { $scope: $scope });
}])

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

DiaryService.GetDiaryEntry($routeParams.id).success(function (data) {
$scope.diaryEntry = data;
});
}]);

You can make the above coding work by building an instance of the base controller in AngularJS and then inject the child controller’s $scope in it. This will add all the properties and methods to the $scope by the base controller in AngularJS, which is available in the child controller and the view.

You may find no sense in the technical Angular controller inheritance in the ‘classical programming’. But this may avert the duplication of code between the controllers in AngularJS.

In below coding, you will find the modified version using “controller as vm” syntax.

AngularJS Base Controller with “Controller as” Syntax
AngularJS-Base-Controller-with-Controller-as-Syntax
'use strict';

angular.module(‘Diary’)
.controller(‘Diary.BaseAddEditController’, DiaryBaseAddEditController)
.controller(‘Diary.AddController’, DiaryAddController)
.controller(‘Diary.EditController’, DiaryEditController);

// Diary.BaseAddEditController
function DiaryBaseAddEditController(vm, DiaryService) {
vm.diaryEntry = { name: ‘default diary entry from Diary.BaseAddEditController’ };

vm.saveDiaryEntry = function () {
DiaryService.SaveDiaryEntry(vm.diaryEntry);
};

// add any other shared functionality here.
}

// Diary.AddController
function DiaryAddController($controller) {
var vm = this;

// instantiate base controller
$controller(‘Diary.BaseAddEditController’, { vm: vm });
}

// Diary.EditController
function DiaryEditController($routeParams, DiaryService, $controller) {
var vm = this;

// instantiate base controller
$controller(‘Diary.BaseAddEditController’, { vm: vm });

DiaryService.GetDiaryEntry($routeParams.id).success(function (data) {
vm.diaryEntry = data;
});
}

Conclusion

After all this juggling and picking, you got the complete guide to AngularJS. Now you are familiar with the controllers, AngularJS extend controller, base controllers, and the tricks that you can do using them. Now it’s your turn to do some brainstorming and show your creativity. Who knows if you will come up with the most innovative idea yet in the market?

We would appreciate you to do some brain work, using above references, and implement your ideas to get extraordinary results. In case you need assistance, you can consult Angular Development company anytime to do some magic with AngularJS.

Need Better AngularJS Architecture Control?

Manage controller inheritance and shared logic effectively.

Improve Architecture

Frequently Asked Questions

What is the best way to extend a controller in AngularJS?

Inject the $controller service into the child controller and use angular.extend to copy methods and properties from the parent. This approach ensures consistent behavior across views and reduces repetitive code in enterprise dashboards.

When should developers use controller inheritance instead of services?

Use inheritance when multiple views share UI logic or $scope properties. For purely data-driven logic or cross directive functionality, services or factories maintain modularity, enabling reusable, maintainable and testable enterprise code.

What are common use cases for extending controllers?

Extending controllers is ideal for dashboards with shared filters, forms with repeated validation, or nested components with identical workflows. This approach accelerates development, reduces code duplication and ensures uniform behavior across complex AngularJS applications.

How can dependency injection be managed efficiently in extended controllers?

Pass required services, factories, or constants via $controller during child instantiation. This preserves modular architecture, prevents redundancy and ensures all inherited methods interact with the same enterprise-level services consistently.

How can I handle errors in extended AngularJS controllers?

Use $scope.$watch or $rootScope error handlers to capture runtime issues. Logging parent and child controller errors improves debugging speed, enhances stability and ensures enterprise dashboards and reporting tools remain reliable.

Resources from your Leaders in Digital Product Builds

We are passionate about discussing recent technologies and their applications, constantly writing blogs and articles in the field. Don't miss out on our detailed and insightful write-ups. Review all our latest blogs and updates here.

.NET App Development for Enterprise: Why It’s the Ideal Choice for Large-Scale Projects
.NET App Development for Enterprise: Why It’s the Ideal Choice for Large-Scale Projects
Harikrishna Kundariya
Harikrishna Kundariya
CEO, eSparkBiz
A Comprehensive Guide to Selecting the Right Tech Stack for Mobile Apps
A Comprehensive Guide to Selecting the Right Tech Stack for Mobile Apps
Harikrishna Kundariya
Harikrishna Kundariya
CEO, eSparkBiz
A Complete Guide to Enterprise Application Integration
A Complete Guide to Enterprise Application Integration
Harikrishna Kundariya
Harikrishna Kundariya
CEO, eSparkBiz
75+ Mobile App Usage Statistics to Plan Successful App Development
75+ Mobile App Usage Statistics to Plan Successful App Development
Agrawal Jigar SEO
Jigar Agrawal
Digital Growth Hacker, eSparkBiz