繁体   English   中英

在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:

结论

感谢您提前提出任何建议。

更新

解决方案在这里存在(再次感谢Scott)。

我不确定到底为什么不能只有一个指令,但是类似以下的方法可能有效。 无需重复父指令,您只需传递模型并让该指令重复并创建每个子指令即可。

      <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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM