Angular 1.5 Component Communication (Parent/Child)

3 February 2017By Rich @Black Sand Solutions
  • AngularJS

Angular 2 is all about components. Everything is a component, even the application itself. With the introduction of the component method in Angular 1.5 we can start building our applications in this manner in Angular 1.

Angular 1.5 Component Communication (Parent/Child)

Angular 2 is all about components. Everything is a component, even the application itself. With the introduction of the component method in Angular 1.5 we can start building our applications in this manner in Angular 1.

Most components should be dumb - that is not modify the state passed in. Instead they should pass any changes back to their parent - which will often be a smart component - by calling a method on the parent component. The method to call is passed in via the components bindings using the binding syntax &.

If they need new data they should request it from the parent. Generally, the child will raise events in response to user action. The parent will then decide if the data needs updating and if so, refresh it and pass it back in.

This post details the steps involved...

Step One

Add a binding on the child component that needs to notify it's parent (this is an output).
The child component will notify the parent of a change by calling this method.

.component('childComponent', {
    bindings: {
         onResultsListUpdated: '&'
    },

Step Two

Call the method whenever we need to notify the parent.

.component('childComponent', {
      controller: function () {
      //wherever we need to call it
      $ctrl.onResultsListUpdated({ results: $ctrl.searchResults });

Note how we use an object literal to pass any data.

{ results: $ctrl.searchResults }

Step Three

Create a (callback) method in the parent controller to handle this update.

.component('parentComponent', {
      controller: function () {

      $ctrl.updateResults = updateResults;

    //note the paramater name
    function updateResults(results) {  }

Step Four

Pass this method to the child component via it's binding.
Again, note how the param name is used.

 <child-component on-results-list-updated="$ctrl.updateResults(results)"></child-component>

Common Errors

Cannot use 'in' operator to search for '$ctrl' in 1
In this case you have called the method, and passed a parameter, but not used JSON object syntax.
i.e. you have done

ng-click="$ctrl.onTabClicked(index)"

instead of

ng-click="$ctrl.onTabClicked({index:1})"
All Posts