简体   繁体   中英

Combine ngRepeat and conditional directive

I'm trying to learn some AngularJS for a project. In my model I have a list of elements that can be of different types. Now I want to show them in a table that looks similar to this example:

<table>
  <tr><td>nameA</td><td>...</td><td>...</td></tr>         <!-- elements of type A -->
  <tr><td>nameB</td><td colspan="2">...data...</td></tr>  <!-- elements of type B -->
  <tr><td>nameC</td><td>...</td><td>...</td></tr>         <!-- elements of type A -->
</table>

If the element is of type A, it should be displayed like the first and third table row, if it is of type B, it should be displayed like the second table row.

How do I achieve this with AngularJS? I started with something like the following:

<table>
  <tr ng-repeat="elem in data.elements | orderBy:'name'">
    <td>{{ elem.name }}</td><td>...</td><td>...</td>
  </tr>
</table>

But now all the table rows have the same format of course. I'm not sure how to combine this with some type of conditional directive to use different templates for the table row, depending on elem.type . I would need something like this:

<table>
  <tr ng-repeat="elem in data.elements | orderBy:'name'">
    <pseudo-tag ng-if="elem.type == 'typeA'">
      <td>{{ elem.name }}</td><td>...</td><td>...</td>
    </pseudo-tag>
    <pseudo-tag ng-if="elem.type == 'typeB'">
      <td>{{ elem.name }}</td><td colspan="2">...data...</td>
    </pseudo-tag>
  </tr>
</table>

What is the AngularJS-y way to achieve this?

You shouldn't need a pseudo-tag because ng-if can be applied directly to td . Something like this should work:

<table>
  <tr ng-repeat="elem in data.elements | orderBy:'name'">
    <td ng-if="elem.type == 'typeA' || elem.type == 'typeB'">{{ elem.name }}</td>
    <td ng-if="elem.type == 'typeB'" colspan="2">...data...</td>
    <td ng-if="elem.type == 'typeA'">...</td>
    ...
  </tr>
</table>

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