Angular 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 上的按钮单击做出反应.
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(container, dataset, options);
.稍后,我想从 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.
推荐答案
在 angular 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);
}
这是一个完整的架构概述:组件通信
这篇关于Angular 1.5 中的组件通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!