angularjs pass grandparent to grandson with components

南楼画角 提交于 2019-12-12 17:02:38

问题


let me give an example if I could with 3 components:

<grandparent>
    <parent>
        <grandson>

If grandparent has an object, let us say a person

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

How would the grandson be able to inherit that value from grandparent?

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

won't work because the $ctrl would be the parent.

hoping that my lighthearted example is taken as such.


回答1:


Check this plunkr

Here is the updated code:

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

You need to provide something like below to make that happen:

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



回答2:


You have few options here:

  1. Drill down the person object, pass it to the parent and the from the parent to the grandson

  2. Use a service to store the person object and the in grandson use that service to get the person object

  3. Use pattern like redux




回答3:


From the Docs:

Intercomponent Communication

Directives can require the controllers of other directives to enable communication between each other. This can be achieved in a component by providing an object mapping for the require property. The object keys specify the property names under which the required controllers (object values) will be bound to the requiring component's controller.

— AngularJS Developer Guide - Intercomponent Communication

For more information, see AngularJS Comprehensive Directive API Reference - require



来源:https://stackoverflow.com/questions/50390843/angularjs-pass-grandparent-to-grandson-with-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!