admin管理员组

文章数量:1293660

I'm wondering if there is a simple solution to this type of problem.

I have an object ment, which can in turn contain ments, and those ments can also contain ments ...and this can go on for a unknown number of cycles.

Here is an example of the data structure:

var ment = {
   text : "",
   ments: [
      { text: "", ments : []},
      { text: "", ments: [
         { text: "", ments : []},
         { text: "", ments : []}
         { text: "", ments : []}
      ]}
   ]
}

Lets say for 2 levels of ments I would write:

<div ng-repeat="ment in ments">
   {{ment.text}}
   <div ng-repeat="ment in ments">
      {{ment.text}}
   </div>
</div>

How would I implent my divs for "n" level of nested ments ?

I'm wondering if there is a simple solution to this type of problem.

I have an object ment, which can in turn contain ments, and those ments can also contain ments ...and this can go on for a unknown number of cycles.

Here is an example of the data structure:

var ment = {
   text : "",
   ments: [
      { text: "", ments : []},
      { text: "", ments: [
         { text: "", ments : []},
         { text: "", ments : []}
         { text: "", ments : []}
      ]}
   ]
}

Lets say for 2 levels of ments I would write:

<div ng-repeat="ment in ments">
   {{ment.text}}
   <div ng-repeat="ment in ments">
      {{ment.text}}
   </div>
</div>

How would I implent my divs for "n" level of nested ments ?

Share Improve this question asked Aug 18, 2013 at 1:41 guiomieguiomie 5,1488 gold badges40 silver badges67 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 11

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="ments"></div>

Here is the partial:

<ul>
    <li ng-repeat="c in ments">
      {{c.text}}
      <div ng-switch on="c.ments.length > 0">
        <div ng-switch-when="true">
          <div ng-init="ments = c.ments;" ng-include="'partialComment.html'"></div>  
        </div>
      </div>
    </li>
</ul>

The data model should be a list var ments = [{ ... }].

I created a demo for you and hope it helps.

Demo

You need a recursive directive. Something like this, or probably better this.

本文标签: javascriptngrepeat unknown number of nested elementsStack Overflow