问题
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:
Drill down the person object, pass it to the parent and the from the parent to the grandson
Use a service to store the person object and the in grandson use that service to get the person object
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 therequire
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