4

I try to factor out some common functionality between some of my controllers into a parent controller. I'd like to do this using some sort of inheritance, instead of some sort of service. All examples using the $injector.invoke function rely on the parent's constructor function being in scope. Like this: http://plnkr.co/edit/kva82QyytKQfOafGiVxL?p=preview.

Since I have all my controllers in separate files, I'd like to do something like this:

The parent controller has its own module:

angular.module('app.parent').controller('ParentCtrl', function() {
    this.someMethodProvidedbyParent = ....
});

The child controller extends ParentCtrl using $injector.invoke. How to get ParentCtrl?

angular.module('app.parent.child').controller('ChildCtrl', function($injector) {

    // Somehow need to get ParentCtrl from the angular module 'app.parent'
    $injector.invoke(ParentCtrl, this, {});
});

I assume I could just place ParentCtrl in some object on the global scope, but I'd rather use the angular module system.

2
  • you could use $controller dependancy, $controller('ParentCtrl', {this: this}); should work in child controller Commented Apr 10, 2015 at 10:07
  • Didn't work when I tried. Commented Apr 10, 2015 at 12:04

1 Answer 1

4

Ok I managed to do it with instantiating the parent controller and then using angular.extend like so:

app.controller('ChildCtrl', function($controller) {
  angular.extend(this, $controller('ParentCtrl'));

  // Overriding methods here (after extending `this`)
});

Properties from the parent are copied to this.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice appoarch.. +1 didn't thought about it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.