toddmotto / angularjs-styleguide

AngularJS styleguide for teams
https://ultimateangular.com
5.96k stars 700 forks source link

Dependency injection for base controllers on Inheritance #44

Closed gabzim closed 8 years ago

gabzim commented 9 years ago

The style guide presents this code:

function BaseCtrl () {
  this.doSomething = function () {

  };
}
BaseCtrl.prototype.someObject = {};
BaseCtrl.prototype.sharedSomething = function () {

};

AnotherCtrl.prototype = Object.create(BaseCtrl.prototype);

function AnotherCtrl () {
  this.anotherSomething = function () {

  };
}

My problem is with this line: AnotherCtrl.prototype = Object.create(BaseCtrl.prototype);

See in this case it works because BaseCtrl has no dependencies, but that's hardly the case in most scenarios, so I can't just use Object.create, what do we do then?

gabzim commented 8 years ago

@toddmotto, any clue on this one?

toddmotto commented 8 years ago

Hey @arg20 - sorry, been hella busy over late 2015. So, you could do this:

function BaseCtrl($scope, dep1, dep2) {
  this.foo = function () { // uses dep1/dep2 or whatever };
}

function AnotherCtrl($scope, $controller) {

  var inherited = $controller('BaseCtrl', {
    $scope: $scope
  });

  angular.extend(this, inherited);

  // use this.foo();

}

Does that help in this example :)

gabzim commented 8 years ago

Ah great! thanks man, that's what I was looking for!