I\'m trying to figure out how controller inheritance works. I have three controllers:
var myApp = angular.module(\'app\', []);
myApp.controller(\'MainContro
Here's an example of how controllers can be extended in Angular.
myApp.service('baseCtrl', function () {
this.name = 'base';
this.getName = function() {
return this.name;
};
});
myApp.controller('MainController', ['baseCtrl', function (baseCtrl) {
angular.extend(this, baseCtrl);
this.name = 'main';
}]);
myApp.controller('Child1', ['baseCtrl', function (baseCtrl) {
angular.extend(this, baseCtrl);
this.name = 'child1';
}]);
myApp.controller('Child2', ['baseCtrl', function (baseCtrl) {
angular.extend(this, baseCtrl);
this.name = 'child2';
}]);
It obliges to use controllerAs, which replaces $scope with this, it is especially good for such cases.
Notice the usage of service instead of other Angular service types, it uses new under the hood, so this... statements can be brought right from a controller to separate service.
There are several ways of doing controller inheritance. Here is another approach.
Regarding the original code, there is no 'controller iheritance' in Angular. And $scope prototypical inheritance assumes that
$scope.getName = function() {
return $scope.name;
};
returns $scope.name from the context where it was defined, it is MainController function in your case.