嘿,我有以下组件树:我有一个名为“规则”的根组件和两个名为“rulesPanel”和“rulesEditor”的子组件。
现在我可以在儿子和母亲组件之间创建通信:
rulesEditor可以调用规则组件并在他身上跳转一个事件。
rulesPanel可以调用rules组件并在他身上跳转一个事件。
我想在两兄弟之间进行交流:
规则编辑器和规则面板。
我不想使用 $scope 或 $broadcast,我想通过组件本身的绑定(bind)来完成。 我试图想办法这样做,但我得到的只是我可以调用上层,但不能调用并行层。
编辑: 我的问题与可能的重复不同, 我不想传递数据,我想在一个组件中执行一个函数,然后由于兄弟组件中的单击函数而在兄弟组件中执行另一个函数。
这是我的代码以及到目前为止我所取得的成就:
var app = angular.module("app",[]);
angular.module('app').component('rules', {
template: `
<rules-panel dial-mom="$ctrl.receivePhoneCall(message)">
</rules-panel>
<rules-editor>
</rules-editor>`,
bindings: {
},
controller: rulesController,
});
function rulesController(){
var self = this;
self.receivePhoneCall = function(message){
console.log("Hello Son");
console.log("I got your message:",message)
}
console.log("rulesController")
}
angular.module('app').component('rulesPanel', {
template: `<h1>rulesPanel</h1>
<button ng-click="$ctrl.callMom()">CallMom</button>
<button ng-click="$ctrl.CallBrother()">CallBrother</button>`,
bindings: {
dialMom: '&'
},
controller: rulesPanelController,
});
function rulesPanelController(){
var self = this;
console.log("rulesPanelController");
self.callMom = function(){
console.log("Call mom");
self.dialMom({message:"Love you mom"});
}
self.CallBrother = function(){
console.log("Call brother");
}
}
angular.module('app').component('rulesEditor', {
template: '<h1>rulesEditor</h1>',
bindings: {
},
controller: rulesEditorController,
});
function rulesEditorController(){
console.log("rulesEditorController")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<div ng-app="app">
<rules></rules>
</div>
最佳答案
您可以使用半 Angular 2 组件方法。这意味着您可以使用输入/输出方法来实现此目的。
我会给你一个例子,你可以从中借鉴。
假设您有一个 header 和一个主要组件。
在您想要通知主组件的 header 组件中,您可以引发如下事件:
.component('headerComponent', {
template: `
<h3>Header component</h3>
<a ng-class="{'btn-primary': $ctrl.view === 'list'}" ng-click="$ctrl.setView('list')">List</a>
<a ng-class="{'btn-primary': $ctrl.view === 'table'}" ng-click="$ctrl.setView('table')">Table</a>
`,
controller: function() {
this.setView = function(view) {
this.view = view
this.onViewChange({$event: {view: view}})
}
},
bindings: {
view: '<',
onViewChange: '&'
}
})
使用绑定(bind) View :“<”我们指定 header 组件将能够读取外部内容并将其绑定(bind)为自己的 Controller 的 View 属性。
标题 Controller 可以这样使用:
<header-component view="root.view" on-view-change="root.view = $event.view"></header-component>
另一方面 main 更简单,它只需要定义它接受的输入:
.component('mainComponent', {
template: `
<h4>Main component</h4>
Main view: {{ $ctrl.view }}
`,
bindings: {
view: '<'
}
})
最后将它们连接在一起:
<header-component view="root.view" on-view-change="root.view = $event.view"></header-component>
<main-component view="root.view"></main-component>
这是一个plunker .
关于javascript - 如何在两个组件之间进行通信 - 兄弟组件(Angular 1.5.8),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42495167/