Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Component communication in angular 1.5

Tags:

Angular 1.5 component communication suggestions usually have output bindings to invoke methods on root controllers.

Let's say I have a root component, and two child components.

<root>
    <child-1></child-1>
    <child-2></child-2>
</root>

It'd like to react to a button click on component one by reading a value on component two and then doing something in the root.

For example, child-1 is a directive which wraps a drawing library that attaches a drawing to its DOM node and has a variable to control that drawing.

child-2 has a button. When it is clicked, data from the child-1 variable should be passed on to root which does something with it.

Specifically, child-1 wraps var graph2d = new vis.Graph2d(container, dataset, options);. Later on, I would like to retrieve some information from graph2d and pass it on to root to do something with it.

This boils down to: how can components react to events issued by other components? The inputs and outputs suggestions don't seem to cover that scenario.

like image 221
ipavlic Avatar asked Apr 15 '16 10:04

ipavlic


1 Answers

In angular 1.5 you can use require and/or property bindings (input/output) to communicate.

If you use the require property then your root component would publish an api and your child component would get a reference to the controller:

angular.module('app').component('child1', {
   bindings: {},
   require: {api: '^root'}, //your <root> component
   template: '',
   controller: controller
});

You can then use the methods of the root component in your child component:

$ctrl.api.addWatchedBook();

This is the root component controller function:

$ctrl.addWatchedBook = addWatchedBook;

function addWatchedBook(bookName){

  booksWatched.push(bookName);

}

Here is a complete architectual overview: Component Communications

like image 152
kevinius Avatar answered Nov 15 '22 06:11

kevinius