How do I establish communication between independent components in AngularJS

205 Views Asked by At

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"
    });
});
2

There are 2 best solutions below

1
georgeawg On BEST ANSWER

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

1
Kotha Praneeth Sai On

@georgeawg already answered the question sufficiently. But I feel one should use sessionStorage when storing username or other userDetails because the date in the service gets erased when the user redirects to other pages. Hence storing it once in the sessionStorage can be very helpful.

// Create item:
var myObj = { username: 'admin', privilages: 'RAED' };
$window.sessionStorage.setItem(key, JSON.stringify(myObj));

// Read item:
var item = JSON.parse($window.sessionStorage.getItem(key));