简体   繁体   中英

Component communication in angular 1.5

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM