2016-12-02 72 views
1

我目前有一个父组件和几个子组件。哪种模式更适合?广播与绑定?

<parent-component> 
    <child-component ng-data="$ctrl.object.fieldone"></child-component> 
    <child-component ng-data="$ctrl.object.fieldtwo"></child-component> 
    ... 
    <button ng-click='$ctrl.setEdit();">Edit</button> 
</parent-component> 

每个子组件要么:显示使用一系列代表观看模式的div /跨距的数据或显示使用表示编辑模式形式的元素中的数据。

父组件有一个触发editMode的按钮。

什么是最好的方式来通知孩子组件状态是编辑模式?似乎有很多不同的方式来传递这种状态:父节点可以是Broadcast或父节点的editMode变量可以绑定到子组件。除了这两者之外还有更好的办法吗?

假设远远超过20-30个子组件,并且这些组件将用于不同的视图。

感谢,

回答

1

从理论上讲,广播只能用于应用程序范围的事件。想象一下登录/注销通知,websockets事件等等。

如果您开始使用广播进行小型活动,您的应用程序中随处可见大量事件,并且您不知道哪个触发了哪个事件。

如果您的应用程序足够小,并且仅由父组件和儿童组成,其中主事件将切换编辑模式布尔值,那么使用广播就可以。

对于任何比这个更大的东西,你可以明显地使用绑定。 在你的特定情况下,它会让你的30个孩子中的每一个都添加一个属性。你可以使用require这个事实。通过要求每个子组件中的父代,您可以自动使用其属性。通过这种方式,您可以传递一个editMode变量,并且在将来需要传递更多数据时,它可以扩展。

var parent = { 
 
    controller: ParentController, 
 
    template:` 
 
    <button ng-click="$ctrl.editionMode = !$ctrl.editionMode">Edition</button> 
 
    <br><br> 
 
    <child></child> 
 
    ` 
 
} 
 

 
function ParentController() { 
 
    this.editionMode = false; 
 
} 
 

 
var child = { 
 
    require: { parent: '^^parent' }, 
 
    controller: ChildController, 
 
    template: ` 
 
    <input type="text" ng-model="$ctrl.value" ng-if="$ctrl.parent.editionMode"> 
 
    <span ng-if="!$ctrl.parent.editionMode">{{$ctrl.value}}</span> 
 
    ` 
 
} 
 

 
function ChildController() { 
 
    this.value = "edit me"; 
 
} 
 

 
angular.module('myApp', []); 
 
angular.module('myApp') 
 
    .component('parent', parent) 
 
    .controller('ParentController', ParentController) 
 
    .component('child', child) 
 
    .controller('ChildController', ChildController);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script> 
 
<div ng-app="myApp"> 
 
    <parent></parent> 
 
</div>

+0

“在html元素上感觉有点沉重,为你的30个孩子添加属性。” - 这正是我的感受。虽然它会起作用,但我并不觉得仅仅简单地表示editState就可以添加额外的属性。 – user2340824

1

概述

$broadcast将事件调度name下所有子作用域(及其子女)通知注册$rootScope.Scope听众......简单地把它涓滴功能发布活动。如果我选择不使用$ rootScope,则使用$broadcast将创建对$ rootScope.then的依赖关系,那么我的控制器必须了解$ scope层次结构并能够相应地$broadcast。这里有趣的部分...尝试测试!基于事件的方法可能会非常杂乱,无法跟踪,维护和调试。这使得它非常异步,没有真正的简单的方法来跟踪应用程序的流程

binding数据绑定在角应用是模型和视图组件之间的数据的自动同步。 Angularjs具有单向和双向数据绑定(请参阅参考资料)这很快引导我谈论范围,因为在绑定时必须知道范围层次结构和视图才能访问,这很容易......

+0

就这样,对业绩的基础上,我建议您了解更多关于绑定和使用它们。它会保持你的系统健全并减少错误 [1]:https://docs.angularjs.org/guide/databinding [2]:https://toddmotto.com/all-about-angulars-emit-broadcast -on-publish-subscription/ [3]:https://docs.angularjs.org/guide/scopetid –

相关问题