简体   繁体   中英

Nesting ng-repeat at single level of DOM

I have nested collections, as follows:

[
  {
    name:    "foo",
    members: ["foo1","foo2"]
  }, {
    name:    "bar",
    members: ["bar1","bar2","bar3"]
  }, {
    name:    "qux",
    members: []
  }
]

From this, I would like to generate the following markup:

<tbody>
  <tr>
    <th scope="row" rowspan="2">foo</th>
    <td>foo1</td>
  </tr><tr>
    <td>foo2</td>
  </tr><tr>
    <th scope="row" rowspan="3">bar</th>
    <td>bar1</td>
  </tr><tr>
    <td>bar2</td>
  </tr><tr>
    <td>bar3</td>
  </tr>
</tbody>

It would also be acceptable to repeat the <th> cells in each row, if rowspan proves too awkward to work with:

<tbody>
  <tr>
    <th scope="row">foo</th>
    <td>foo1</td>
  </tr><tr>
    <th scope="row">foo</th>
    <td>foo2</td>
  </tr><tr>
    <th scope="row">bar</th>
    <td>bar1</td>
  </tr><tr>
    <th scope="row">bar</th>
    <td>bar2</td>
  </tr><tr>
    <th scope="row">bar</th>
    <td>bar3</td>
  </tr>
</tbody>

What is the idiomatic way to accomplish a task like this using AngularJS? In particular, I'm struggling to see how one can perform a nested ng-repeat at a single level of the DOM (ie on the <tr> element).

You can't add several repeats on one tag. But you can add ng-repeat to tbody into your table

<table>
  <tbody ng-repeat="row in data">
     <tr ng-repeat="member in row.members">
       <th scope="row" rowspan="{{row.members.length}}" ng-if="$first">{{row.name}}</th>
       <td>{{member}}</td>
    </tr>
  </tbody>
</table>

Then you can hide extra th 's using ng-if and $first – this is local property in ng-repeat which becomes true on first element in repeat.

Look at JSBin with result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM