代码之家  ›  专栏  ›  技术社区  ›  Saqib Ali

Angular:如何用两个以上的类替换列表中的CSS类?

  •  2
  • Saqib Ali  · 技术社区  · 9 年前

    我有以下内容 Angular template 。这很好地交替了每行的样式类,以便 even-numbered rows 只有一节课 odd-numbered rows 拥有不同的类别:

    <tbody>
      <tr ng-repeat="currElement in myCtrl.elementList track by $index" >
        <td ng-class-odd="'element-tilt-left'" ng-class-even="'element-tilt-right'">
          <a ui-sref="myState({elementId: currElement.elementId)" ng-bind="currElement.name">
          </a>
        </td>
      </tr>
    </tbody>
    

    但现在我想在4个不同的样式类之间循环,而不是仅仅在两个样式类之间。我该怎么做?

    4 回复  |  直到 9 年前
        1
  •  5
  •   grayimp    9 年前

    ng-class="'class' + $index%4"
    

    以下是对他的小提琴的更新: http://jsfiddle.net/uL5zd8sy/1/

        2
  •  4
  •   Phil    9 年前

    您应该只能将CSS与 nth-child

    angular.module('so', []).run(function($rootScope) {
      $rootScope.elementList = [1, 2, 3, 4, 5, 6, 7, 8, 9].map(function(i) {
        return { name: 'Item ' + i };
      });
    });
    tr:nth-child(4n-3) td {
      background-color: red;    /* Style #1 */
    }
    tr:nth-child(4n-2) td {
      background-color: green;  /* Style #2 */
    }
    tr:nth-child(4n-1) td {
      background-color: blue;   /* Style #3 */
      color: white;
    }
    tr:nth-child(4n) td {
      background-color: black;  /* Style #4 */
      color: white;
    }
    <table ng-app="so">
      <tbody>
        <tr ng-repeat="currElement in elementList track by $index">
          <td>
            <a ng-bind="currElement.name"></a>
          </td>
        </tr>
      </tbody>
    </table>
    
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
        3
  •  2
  •   Divyanshu Maithani    9 年前

    您可以尝试以下操作:

    ng-class="{class1 : $index%4 == 0, class2 : $index%4 == 1, class3 : $index%4 == 2, class4 : $index%4 == 3}"
    

    退房 this 不停摆弄

        4
  •  0
  •   Samuel    9 年前

    希望 this would be helpful .

    .row:nth-child(4n+1){
      color: red;
    }
    
    .row:nth-child(4n+2){
      color: green;
    }
    
    .row:nth-child(4n+3){
      color: grey;
    }
    
    .row:nth-child(4n+4){
      color: blue;
    }
    

    这将节省角度消化周期