【问题标题】:angularjs pass grandparent to grandson with componentsangularjs用组件将祖父母传给孙子
【发布时间】:2018-05-17 11:55:37
【问题描述】:

如果可以的话,我举个例子:

<grandparent>
    <parent>
        <grandson>

如果祖父母有一个对象,让我们说一个人

const person = {
    name: 'William',
    age: 102
}

孙子如何能够从祖父母那里继承该价值?

<title={{ $ctrl.person.name }}>

不起作用,因为 $ctrl 将是父级。

希望我的轻松示例被这样看待。

【问题讨论】:

标签: angularjs angularjs-components


【解决方案1】:

Check this plunkr

这是更新后的代码:

<grand-parent>
  <cbs-cus-comp com-bind='grandParentCntAs.name'>
    <child child-com-bind='cbsCusCompCntAs.name'></child>
  </cbs-cus-comp>
</grand-parent>

您需要提供如下内容才能实现:

  var cbsCusComp        =   {
                            transclude  :   true,
                            require: {grandParentComp:'^grandParent'},
                            template    :   'Parent : <b>{{cbsCusCompCntAs.comBind}}</b><br /><ng-transclude></ng-transclude>',
                            controller  :   cbsCusCompCnt,
                            controllerAs:   'cbsCusCompCntAs',
                            bindings    :   {comBind:'='}
                        };

【讨论】:

  • 谢谢。我对我的问题进行了编辑,因为我提到这些是组件。
  • @pertrai1 任何 cmets ?
【解决方案2】:

你有几个选择:

  1. 向下钻取 person 对象,将其传递给父对象以及从父对象传递给孙子对象

  2. 使用服务来存储人员对象,而孙子使用该服务来获取人员对象

  3. 使用redux之类的模式

【讨论】:

【解决方案3】:

来自文档:

组件间通信

指令可以require其他指令的控制器来实现彼此之间的通信。这可以通过为require 属性提供对象映射在组件中实现。对象键指定所需控制器(对象值)将在其下绑定到所需组件的控制器的属性名称。

— AngularJS Developer Guide - Intercomponent Communication

欲了解更多信息,请参阅AngularJS Comprehensive Directive API Reference - require

【讨论】: