P
P
pavtaras2016-07-26 11:27:35
JavaScript
pavtaras, 2016-07-26 11:27:35

How to correctly inherit a controller in angular?

Essence of the question. There are two controllers:

angular.module('app', [])
  .controller('AbstractCtrl', AbstractCtrl)
  .controller('AppCtrl', AppCtrl);

Let's leave the abstract controller code unchanged:
function AbstractCtrl(){
  var self = this;

  self.name = "Vova";

  self.init = function(){
    self.name = "Petya";
  };
}

But we inherit the second controller in two ways and call initialization:
method number 1:
function AppCtrl($controller){
  var vm = this;
  angular.extend(vm, $controller('AbstractCtrl', {}));
  vm.init();
}

method number 2:
function AppCtrl(){
  var vm = this;
  AbstractCtrl.call(this);
  vm.init();
}

There is a significant difference as well. After initializing the controller inherited in the first way, we will have the name Vova, the second way - Petya. It is clear that we are waiting for Petya. And it is clear that this abstract controller can be rewritten here so that both times it will be Petya. But rewriting is not good, especially since the code is correct.
In total, inheritance in the second way seems to me more universal. But often developers write controllers:
a) with anonymous functions and there is no possibility
b) they separate the code into files and even use self-calling functions so as not to clog the global scope. As a result, we do not see the required function in the file of another controller and cannot inherit it. It is possible to store, for example, a collection of all controllers in window.controllers, but this seems like a hassle.
How to get out of this situation? Maybe there is some kind of getter in angular that will allow you to get the controller function? For example, angular.get('AbstractCtrl'). Or in general any other, more perfect way of inheritance?
Thank you.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
N
napa3um, 2016-07-26
@pavtaras

function AppCtrl($scope, $controller) {
  $controller('AbstractCtrl', { $scope: $scope });
}

// или

function AppCtrl($controller) {
  $controller('AbstractCtrl', { vm: this });
}

P
pavtaras, 2016-07-26
@pavtaras

I myself see as an option to write a factory that returns the desired function, which can be further injected into the controller and called via .call. But this is some kind of crutch and is not suitable for non-abstract controllers

Y
yociyavi, 2016-07-26
@yociyavi

Move the common functionality to a service, and in each controller, merge this service from this controller

R
Roman Ogarkov, 2016-07-26
@ogarich89

If you need a common function for many controllers, create a factory

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question