AngularJS, JavaScript

AngularJS: How to Get The Controller of Another Component

Or perhaps it should be called “How to get rid of the $parent.$parent.$parent...$parents in your code”, or “How do components talk to one another”.

There are a couple of ways to deal with it.

1. Getting Parent Component Controller from Child Component Controller

This comes down to the fact that in AngularJS, “components can require the controllers of other components to enable communication between each other.”

Say we have the structure:

<parent-component>
  <child-component></child-component>
</parent-component>

Then in the ChildComponent registration, we can do:

app.component('childComponent', {
  require: {
     parentComponentCtrl: '^parentComponent'
  },
  controller: () => {
     // parent component controller can be accessed like this:
     console.log(this.parentComponentCtrl);
  },
});

For more explanation, see example: requiring ng model as component and documentation on component.

2. Getting Child Component Controller from Parent Component Controller

With the same html structure, in ParentComponent we would have:

Then in the ChildComponent registration, we can do:

app.component('parentComponent', {
  controller: ($element) => {
     // child component controller can be accessed like this:
     const childCtrl = $element.find('child-component').controller('controller-name');
  },
});

For more explanation, see example: requiring ng model as component and documentation on component.

3. Getting A Component Controller from Anywhere in The App

You might have noticed from the second example that you can get the controller of a component by calling .controller() on the component element. Another trick is that you can also get the scope of any node by calling .scope() of the node, which can be very useful when debugging.

When debugging a page with chrome dev tools, $0 in the console will give you the node that is currently selected. Combining the two, you can get the controller and scope of any element on the page easily:

Happy coding and debugging! 😀

Standard

One thought on “AngularJS: How to Get The Controller of Another Component

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.