Component communication in angular 1.5

泪湿孤枕 提交于 2020-02-28 04:47:05

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/36645065/component-communication-in-angular-1-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!