我正在尝试动态构建ng-template,在数据结构中,我有一个包含相同类型或其他类型的对象列表的对象。
[
{
type: "device",
id: 1,
allowedTypes: ["device","action"],
max: 5,
columns: [
{
type: "action",
id: "1"
},
{
type: "device",
id: 2,
allowedTypes: ["device","action"],
max: 5,
columns: [
{
type: "action",
id: "1"
},
{
type: "action",
id: "2"
}
]
}
]
}
]我的ng模板代码:
<script type="text/ng-template" id="and.html">
<div class="container-element box box-red">
<h3>And {{item.id}}</h3>
<ul dnd-list="item.columns"
dnd-allowed-types="item.allowedTypes"
dnd-disable-if="item.columns.length >= item.max">
<li ng-repeat="element in item.columns"
dnd-draggable="element"
dnd-effect-allowed="move"
dnd-moved="item.columns.splice($index, 1)"
dnd-selected="models.selected = element"
ng-class="{selected: models.selected === element}"
ng-include="element.type + '.html'" onload="onloadAction()">
</li>
</ul>
<div class="clearfix"></div>
</div>
</script>在ng-template代码中,可以很容易地添加第一级或不同类型的对象,但是当添加到第二级时,相同类型的对象不能正常工作,似乎是在一个递归循环中。这是因为嵌套的ng模板(子)ng模板使用了来自ng- item.columns =“item.columns中的元素”的根重复。
<li ng-repeat="element in item.columns"
dnd-draggable="element"
ng-include="element.type + '.html'">
</li>

如何解决此问题的任何建议。
发布于 2017-01-14 19:29:25
我已经设法解决了这个问题,ng-repeat创建了一个新的子作用域,但是来自父作用域的项在子作用域中也是可见的,因为这是递归的,意思是子模板和父模板都有同名的变量item。但是,忽略子范围变量item:
<li ng-repeat="element in item.columns"
dnd-draggable="element"
ng-include="element.type + '.html'">
</li>在上面的代码片段中,元素还有一个名为item的变量,因此在子范围内,当我们调用item.columns时,父范围的项变量再次被调用,为了确保子范围的项变量不被忽略,我们需要使用ng-init和ng-include,并在子范围内将当前元素设置为项,如下所示:
<li ng-repeat="element in item.columns"
dnd-draggable="element"
ng-include="element.type + '.html'" ng-init="item=element">
</li>要了解更多信息,请访问http://benfoster.io/blog/angularjs-recursive-templates
https://stackoverflow.com/questions/41644772
复制相似问题