【发布时间】:2017-07-18 14:56:00
【问题描述】:
嘿,我有以下组件树:我有一个名为 rules 的根组件和两个名为 rulesPanel 和 rulesEditor 的子组件。
现在我可以创建子组件和母组件之间的通信了:
rulesEditor 可以调用规则组件并在他身上跳转一个事件。
rulesPanel 可以调用规则组件并在他身上跳转一个事件。
我想在两兄弟之间进行交流:
rulesEditor 和 rulesPanel。
我不想使用 $scope 或 $broadcast,我想通过组件自己的绑定来做到这一点。 我试图想办法这样做,但我得到的只是我可以调用上层但不能调用并行级别。
编辑: 我的问题与可能的重复不同, 我不想传递数据,我想在一个组件中执行一个函数,然后由于兄弟组件中的单击函数而在兄弟组件中执行另一个函数。
这是我的代码以及我目前所取得的成就:
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>
【问题讨论】:
-
这可以通过父组件或通过公共服务来完成。这取决于具体情况哪种方式更好。如果只有一个“规则”,服务应该很好。
-
我有一个称为规则的父组件,我不需要为此提供服务。你能给我一个例子,说明子组件中发生的点击事件如何触发兄弟组件上的事件吗?感谢您的帮助。
-
通常在 MV* 框架中,事件不会横向或向下传递。事件向上传达;模型值向下传达。在多个地方进行状态更改违反了Single Source of Truth 原则。
-
我的错这真的是重复
标签: javascript angularjs