Can an AngularJS controller inherit from another controller in the same module?

Federico Elles picture Federico Elles · Aug 27, 2013 · Viewed 87.7k times · Source

Within a module, a controller can inherit properties from an outside controller:

var app = angular.module('angularjs-starter', []);

var ParentCtrl = function ($scope, $location) {
};

app.controller('ChildCtrl', function($scope, $injector) {
  $injector.invoke(ParentCtrl, this, {$scope: $scope});
});

Example via: Dead link: http://blog.omkarpatil.com/2013/02/controller-inheritance-in-angularjs.html

Can also a controller inside a module inherit from a sibling?

var app = angular.module('angularjs-starter', []);

app.controller('ParentCtrl ', function($scope) {
  //I'm the sibling, but want to act as parent
});

app.controller('ChildCtrl', function($scope, $injector) {
  $injector.invoke(ParentCtrl, this, {$scope: $scope}); //This does not work
});

The second code does not work since $injector.invoke requires a function as first parameter and does not find the reference to ParentCtrl.

Answer

Salman von Abbas picture Salman von Abbas · Nov 27, 2013

Yes, it can but you have to use the $controller service to instantiate the controller instead:-

var app = angular.module('angularjs-starter', []);

app.controller('ParentCtrl', function($scope) {
  // I'm the sibling, but want to act as parent
});

app.controller('ChildCtrl', function($scope, $controller) {
  $controller('ParentCtrl', {$scope: $scope}); //This works
});