ng-repeat 未知数量的嵌套元素 [英] ng-repeat unknown number of nested elements

查看:30
本文介绍了ng-repeat 未知数量的嵌套元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有解决此类问题的简单方法.

我有一个对象注释,它可以反过来包含注释,而这些注释也可以包含注释……而且这可以持续未知数量的循环.

这是一个数据结构的例子:

var 注释 = {文本 : "",注释: [{文字:",评论:[]},{ 文字:",评论:[{文字:",评论:[]},{ 文字:",评论:[]}{ 文字:",评论:[]}]}]}

假设我会写 2 个级别的评论:

{{comment.text}}<div ng-repeat="评论中的评论">{{comment.text}}

我将如何将我的 div 用于n"级嵌套评论?

解决方案

最简单的方法是创建一个通用部分,以便您可以使用 ng-include 递归调用和渲染它.

<div ng-include="'partialComment.html'" ng-model="comments"></div>

这是部分:

    <li ng-repeat="c 在评论中">{{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>

数据模型应该是一个列表var comments = [{ ... }].

我为您创建了一个演示,希望对您有所帮助.

演示

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 ?

解决方案

The easiest way is to create a generic partial so you can recursively call and render it using 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 = [{ ... }].

I created a demo for you and hope it helps.

Demo

这篇关于ng-repeat 未知数量的嵌套元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆