2

I want to use the vm convention of controllers writing. The problem is that I faced with is inheritance, for example lets assume I have the following:

Base Controller:

  angular.module('app')
    .controller('BaseCtrl', BaseCtrl);

  function BaseCtrl() {
    var vm = this;
    vm._privateVar = 1;
  }

  BaseCtrl.prototype.foo= function() {
    console.log('foo')
  };

Child Controller:

  angular.module('app')
    .controller('ChildCtrl', ChildCtrl);

  function ChildCtrl() {
    var vm = this;
  }

  ChildCtrl.prototype.goo= function() {
    console.log('goo')
  };

Note:
I have an access to injection only within the ChildCtrl function:

function ChildCtrl(/*I can inject here only*/) {
    var vm = this;
} 

Also, The BaseCtrl is not a global class/function/object. Is there is any whay to inject the controller service outside of the controller function?

How should I make ChildCtrl inherit form BaseCtrl?
Thanks!

Community
  • 1
  • 1
vlio20
  • 8,955
  • 18
  • 95
  • 180

2 Answers2

1

Eventually I made the following,

  //get the injector.
  var injector = angular.injector(['app']);

  //get the service.
  var $controller = injector.get('$controller');
  var BaseCtrl = $controller('BaseCtrl');

  angular.module('app')
    .controller('ChildCtrl', ChildCtrl);

  function ChildCtrl() {
     var vm = this;
     BaseCtrl.call(this);
  }

  ChildCtrl.prototype = Object.create(BaseCtrl);

As you can see I have injected the $controller service got the BaseCtrl with it.

I know this is ugly as hell and I will glad to hear better suggestions;

vlio20
  • 8,955
  • 18
  • 95
  • 180
0

in your child controller you can do:

function ChildCtrl() {
  var vm = this;
  BaseCtrl.call(this);
}

ChildCtrl.prototype = Object.create(BaseCtrl);

With this approach BaseCtrl would need to be global. You could get similar code reuse with a mixin and it wouldn't use a global but you won't get anything off of the base prototype. e.g.:

var BaseCtrlMixinService = function() {
  this.myValue = 123;
  this.myFunc = function() {
    console.log(this.myValue);
  }
}

angular.module('app').service('baseCtrlMixin', BaseCtrlMixinService);


function ChildCtrl(baseCtrlMixin) {
  var vm = this;
  angular.extend(this, baseCtrlMixin);
}

angular.module('app').controller('ChildCtrl', ChildCtrl);
rob
  • 17,995
  • 12
  • 69
  • 94