Can an AngularJS controller inherit from another controller in the same module?
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});
In case you are using vm
controller syntax, here is my solution:
.controller("BaseGenericCtrl", function ($scope) { var vm = this; vm.reload = reload; vm.items = []; function reload() { // this function will come from child controller scope - RESTDataService.getItemsA this.getItems(); }}).controller("ChildCtrl", function ($scope, $controller, RESTDataService) { var vm = this; vm.getItems = RESTDataService.getItemsA; angular.extend(vm, $controller('BaseGenericCtrl', {$scope: $scope}));})
Unfortunately, you can't use $controller.call(vm, 'BaseGenericCtrl'...)
, to pass current context into closure (for reload()
) function, hence only one solution is to use this
inside inherited function in order to dynamically change context.
I think,you should use factory or service,to give accessible functions or data for both controllers.
here is similar question ---> AngularJS controller inheritance