角度1.5的组件通信 [英] Component communication in angular 1.5
问题描述
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>
它想通过读取组件2上的值来响应组件1上的按钮单击然后在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.
例如, child-1
是一个包装图形库的指令将绘图附加到其DOM节点并具有控制该绘图的变量。
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
有一个按钮。单击它时, child-1
变量中的数据应传递给root,后者会对其执行操作。
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.
具体来说, child-1
换行 var graph2d = new vis.Graph2d(容器,数据集,选项);
。稍后,我想从 graph2d
中检索一些信息并将其传递给 root
以对其进行操作。
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.5中,您可以使用 require 和/或属性绑定(输入/输出)进行通信。
In angular 1.5 you can use require and/or property bindings (input/output) to communicate.
如果使用require属性,则根组件将发布api和你的子组件将获得对控制器的引用:
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);
}
这是一个完整的架构概述:组件通讯
这篇关于角度1.5的组件通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!