javascript 如何使用 ng-repeat 更改 AngularJS 中特定 <tr> 的背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33246583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:16:08  来源:igfitidea点击:

How to change background color for a specific <tr> in AngularJS using ng-repeat

javascripthtmlcssangularjs

提问by Elvira Emm

How can I set a different background color for every row? For exemple:

如何为每一行设置不同的背景颜色?举个例子:

row1: blue

第 1 行:蓝色

row2: red

第 2 行:红色

row3: green

第 3 行:绿色

main.js

主文件

$scope.names = [
        {fName: "John", lName: "David"},
        {fName: "Richard", lName: "Daniel"},
        {fName: "Paul", lName: "Mark"}
        ];

test.html

测试.html

<table class="table table-bordered">
  <tbody><tr ng-repeat="name in names">
    <td>{{name.fName}}</td>
    <td>{{name.lName}}</td>
  </tr></tbody>
</table>

回答by TheBreakthrough

If you would like a different color for each row you could use ngStyle

如果您想为每一行使用不同的颜色,您可以使用 ngStyle

<tr ng-repeat="name in names" ng-style="{'background-color': colors[$index]}">

where your controller states $scope.colors = ['blue','red', 'green']

您的控制器声明的位置 $scope.colors = ['blue','red', 'green']

or

或者

<tr ng-repeat="name in names" ng-class="colors[$index]">

and add each to your style sheet

并将每个添加到您的样式表

.blue { background-color: blue }

回答by Michael P. Bazos

Here is an example, with angular:

这是一个带有角度的示例:

Template:

模板:

<tr ng-repeat="name in names" ng-class="{greenyellow: $index === 1}">
    <td>{{name.fName}}</td>
    <td>{{name.lName}}</td>
</tr>

CSS

CSS

.greenyellow {
    background-color: greenyellow;
}

This will style the second row as $indexis zero-based.

这会将第二行的样式设置$index从零开始

demo fiddle

演示小提琴

回答by Ravikumar Kalimuthuswamy

Below code is used to highlight the selected row .

下面的代码用于突出显示所选行。

<tr ng-repeat="orderList in orderDetailList track by $index"   ng-style="{'background-color': colors[$index]}">

Declare in the controller

在控制器中声明

app.controller("OrderListController",function($scope){
    $scope.colors=[];
    /* call the below function on ng-click
    $scope.addtoship = function(){
        $scope.colors.push(['pink']);
    }
}    

HTML

HTML

<td>
    <button type="button" data-ng-click="addtoship()"> Add to Ship </button>
</td>