在AngularJS中,如何在父指令中嵌入变量子指令?

时间:2014-12-22 18:48:14

标签: javascript angularjs angularjs-directive

简介

对于我正在进行的项目,我正试图以“棱角分明的方式”解决一个特定的问题,但是我认为我必须遗漏一些东西,因为无论我尝试什么,我都会继续达到砖头壁。

这个问题的关键是我从后端动态加载数据,后端描述了用户可见的不同组件。这不是问题本身,而是特定和问题的问题。适当的角度'改变模型列表的方法'将组件描述为实际呈现的HTML。

问题

我想要创建的内容基本上如下:

从一个父指令开始,该指令使用ng-repeat作为范围列表名为" models",其中包含零个或多个"组件":

<parent-directive ng-repeat="model in models" model="model"></parent-directive>

ng-repeat指令使用不同的&#39;模型&#39;创建该原始指令的N个副本。参数(对于$ scope.models数组中的每个对象)。

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

的问题! =&gt; 根据javascript对象中包含的数据(在本例中,称为&#39; type&#39;),parentdirective会转换为特定的子指令:

<parent-directive model="..."></parent-directive>

变成

<child-directive-one model="..."></child-directive-one>

<child-directive-two model="..."></child-directive-two>

取决于什么值&#39; model.type&#39;是

然后,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:

结论

感谢您提前获得任何建议。

更新

Solution exists here (thanks again to Scott).

1 个答案:

答案 0 :(得分:2)

我不确定为什么你不能只有一个指令,但是下面的东西可能会起作用。您只需传入模型并使该指令重复并创建每个子指令,而不是重复父指令。

      <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>
相关问题