![](/img/trans.png)
[英]How do I pass a Child Directive's Data to a Parent Directive in AngularJS
[英]In AngularJS, how can I nest variable child directive(s) inside a parent directive?
介紹
對於我正在從事的項目,我正在嘗試以“角度方式”解決一個特定的問題,但是我認為我一定會缺少一些東西,因為無論我嘗試什么,我都會繼續接觸磚牆。
這個問題的症結在於,我正在從后端動態加載數據,該數據描述了用戶可見的不同組件。 這不是問題本身,而是問題的具體和正確的“角度”方式,以將描述組件的“模型”列表轉換為實際呈現的HTML。
問題
我要創建的基本上是以下內容:
首先使用父指令,該指令將ng-repeat用於名為“模型”的作用域列表,該列表包含零個或多個“組件”:
<parent-directive ng-repeat="model in models" model="model"></parent-directive>
ng-repeat指令使用不同的“模型”參數(針對$ scope.models數組中的每個對象)創建該原始指令的N個副本。
// this is just for demonstrative purposes, it obviously looks different in source
<parent-directive model="child1"></parent-directive>
<parent-directive model="child2"></parent-directive>
<parent-directive model="child3"></parent-directive>
問題! =>根據包含在javascript對象中的數據(在這種情況下,稱為“類型”),將parentdirective轉換為特定的子指令:
<parent-directive model="..."></parent-directive>
變成
<child-directive-one model="..."></child-directive-one>
要么
<child-directive-two model="..."></child-directive-two>
取決於值'model.type'是什么。
然后,child指令使用傳遞給它的數據將其呈現為自己的自定義HTML(超出此問題的范圍)。 如果我們從上面繼續該示例,那么該HTML應該呈現為以下內容(希望如此):
<child-directive-one model="child1"></child-directive-one>
<child-directive-one model="child2"></child-directive-one>
<child-directive-two model="child3"></child-directive-two>'
其次(這超出了問題的范圍,但只是要看到底),每個指令都呈現為自己的HTML:
<div>in childDirectiveOne, text is: This is text contained inside child1</div>
<div>in childDirectiveOne, text is: This is text contained inside child2</div>
<div>in childDirectiveTwo, text is: This is text contained inside child3</div>
資源
我一直在嘗試許多不同的方法來嘗試使它正常工作(涉及鏈接功能,使用$ compile等),但是此源提供了所有這些嘗試。 這是我到目前為止開發的源代碼:
removed source (was filled with errors). Solution that Scott helped me out with is below:
結論
感謝您提前提出任何建議。
更新 :
我不確定到底為什么不能只有一個指令,但是類似以下的方法可能有效。 無需重復父指令,您只需傳遞模型並讓該指令重復並創建每個子指令即可。
<parent-directive the-models="models"></parent-directive>
父指令模板:
<div ng-repeat="model in models"....>
<child-directive ng-if="YOUR CONDITION"></child-directive>
<child-directive2 ng-if="YOUR CONDITION"></child-directive>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.