How do I establish communication between independent components in AngularJS

Issue

I have a Nav in which there are two pages representing two AngularJS components – Home and About. I want to pass user name from Home component to About component.

<div ng-app="myApp">
  <ul>
    <li><a href="#!/home">Home</a>
    </li>
    <li><a href="#!/about">About</a>
    </li>
  </ul>
  <div ng-view></div>
</div>

I tried to establish the component communication using bindings with < but no luck. Basically, they are both independent components. How do I pass data from one component to another in this scenario.

I’ve created a working example using CodePen. Could anyone please guide how to do it.

Components and Route Config

app.component("home", {
  template: `<h1>Home</h1>
              Hi {{$ctrl.user}}!`,
  controller: function HomeController() {
    this.user = "John.";
  }
});

app.component("about", {
  template: `<h1>About</h1>`,
  controller: function AboutController() {}
});

app.config(function($routeProvider) {
  $routeProvider
    .when("/home", {
      template: "<home></home>"
    })
    .when("/about", {
      template: "<about></about>"
    })
    .otherwise({
      redirectTo: "/home"
    });
});

Solution

View data is destroyed when views change. Store data that needs to persist between views in a service:

app.service("appData", function() {
    var user;
    this.setUser= val => user = val;
    this.getUser= _ => user;
});

Use that service in the component controllers:

app.component("home", {
  template: `<h1>Home</h1>
              Hi {{$ctrl.user}}!`,
  controller: function HomeController(appData) {
    this.user = "John.";
    appData.setUser(this.user);
  }
});

app.component("about", {
  template: `<h1>About</h1>`,
  controller: function AboutController(appData) {
      this.user = appData.getUser();
  }
});

For more information, see

Answered By – georgeawg

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.