使用ng-repeat在html表中选择行着色

Alternative row coloring in html table with ng-repeat

本文关键字:选择 ng-repeat html 使用      更新时间:2023-09-26

我有一个使用ng-repeat填充值的表。我需要颜色的行表交替绿色和黄色的颜色。我用下面的方法试了试,没有ng-repeat,效果很好。

.table-striped>tbody>tr:nth-of-type(odd)
    {
        background: yellow !important;
    }
    .table-striped>tbody>tr:nth-of-type(even)
    {
        background: green !important;
    }
<html>
  <div><table class="table table-striped">
        <thead style="border: 1px solid">
            <tr>
                <th>Heading</th>                
            </tr>
        </thead>
        <tbody>
           <tr>
                <td>{{value.val1}}</td>
             </tr>
          <tr>
                <td>{{value.val2}}</td>
            </tr>
          <tr>
                <td>{{value.val3}}</td>
            </tr>            
        </tbody>
    </table>
    </div>
  <html>

但是在使用ng-repeat时不工作,如下所示(所有行本身都是黄色)。请帮助。提前谢谢。

.table-striped>tbody>tr:nth-of-type(odd)
    {
        background: yellow !important;
    }
    .table-striped>tbody>tr:nth-of-type(even)
    {
        background: green !important;
    }
<html>
  <div><table class="table table-striped">
        <thead style="border: 1px solid">
            <tr>
                <th>Heading</th>                
            </tr>
        </thead>
        <tbody ng-repeat="value in values">
           <tr>
                <td>{{value.val1}}</td>
             </tr>
                      
        </tbody>
    </table>
    </div>
  <html>

我认为你应该给ng-repeat="value in values"来代替body。

您可以动态地为您的行添加一个类,然后给出您想要的样式。

<tr class="myrow">
$(".myrow:odd").addClass("odditem");
$(".myrow:even").addClass("evenitem");

你可以使用ng-class-odd="'classname'"指令。

<html>
  <div>
     <table class="table table-striped">
        <thead style="border: 1px solid">
            <tr>
                <th>Heading</th>                
            </tr>
        </thead>
        <tbody ng-repeat="value in values">
           <tr class="row-color" ng-class-odd="'odd'">
                <td>{{value.val1}}</td>
             </tr>
          <tr class="row-color" ng-class-odd="'odd'">
                <td>{{value.val2}}</td>
            </tr>
          <tr class="row-color" ng-class-odd="'odd'">
                <td>{{value.val3}}</td>
            </tr>            
        </tbody>
    </table>
    </div>
  <html>

那么在你的CSS中你可以这样做

.row-color {
    background: green;
}
.row-color.odd {
    background: yellow;
}

这也摆脱了你的!重要,通常被认为是不好的做法。

虽然我认为OP的解决方案是将ng-repeat<tbody>移动到<tr>,因为它与没有ng-repeat的预期结构相匹配;当ng-repeat<tbody>层上时,完全可以通过单独使用css来替换颜色。

tbody:nth-of-type(odd)>tr {
  background-color: pink;
}
tbody:nth-of-type(even)>tr {
  background-color: purple;
}
<table>
  <tbody>
    <tr><td>row1</td></tr>
  </tbody>
  <tbody>
    <tr><td>row2</td></tr>
  </tbody>
  <tbody>
    <tr><td>row3</td></tr>
  </tbody>
</table>