[英]ng-repeat unknown number of nested elements
I'm wondering if there is a simple solution to this type of problem. 我想知道是否有这种问题的简单解决方案。
I have an object comment, which can in turn contain comments, and those comments can also contain comments ...and this can go on for a unknown number of cycles. 我有一个对象注释,它可以包含注释,这些注释也可以包含注释......这可以继续进行未知数量的周期。
Here is an example of the data structure: 以下是数据结构的示例:
var comment = {
text : "",
comments: [
{ text: "", comments : []},
{ text: "", comments: [
{ text: "", comments : []},
{ text: "", comments : []}
{ text: "", comments : []}
]}
]
}
Lets say for 2 levels of comments I would write: 让我们说,我会写两个级别的评论:
<div ng-repeat="comment in comments">
{{comment.text}}
<div ng-repeat="comment in comments">
{{comment.text}}
</div>
</div>
How would I implent my divs for "n" level of nested comments ? 我如何为“n”级嵌套注释实现我的div?
The easiest way is to create a generic partial so you can recursively call and render it using ng-include
. 最简单的方法是创建一个通用部分,以便您可以使用ng-include
递归调用和呈现它。
<div ng-include="'partialComment.html'" ng-model="comments"></div>
Here is the partial: 这是部分:
<ul>
<li ng-repeat="c in comments">
{{c.text}}
<div ng-switch on="c.comments.length > 0">
<div ng-switch-when="true">
<div ng-init="comments = c.comments;" ng-include="'partialComment.html'"></div>
</div>
</div>
</li>
</ul>
The data model should be a list var comments = [{ ... }]
. 数据模型应该是列表var comments = [{ ... }]
。
I created a demo for you and hope it helps. 我为你创建了一个演示,并希望它有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.