简体   繁体   English

如何在 AngularJS 中动态更改表格单元格颜色

[英]How to dynamically change table cell color in AngularJS

I have a view, where I am using ng-repeat to populate a table content with dynamic data.我有一个视图,我使用 ng-repeat 用动态数据填充表格内容。 Here's the code snippet-这是代码片段-

    <tr ng-repeat="x in response">
        <td>{{x.property1}}</td>
        <td>{{x.property2}}</td>
        <td bgcolor="x.color1">{{x.property3}}</td>
        <td bgcolor="x.color2">{{x.property4}}</td>
    </tr>

But the table output is not changing.但是表输出没有改变。 I am getting same color for every response.对于每个响应,我都得到相同的颜色。 How do I actually alter the color?我如何真正改变颜色? You can see the output in this Image .您可以在此Image 中看到输出。 Also, the color that is present is not even supplied to the response.此外,存在的颜色甚至不提供给响应。

How do I solve this?我该如何解决这个问题?

You will need to use ng-style directive for this like:您需要为此使用ng-style指令,例如:

<tr ng-repeat="x in response">
    <td>{{x.property1}}</td>
    <td>{{x.property2}}</td>
    <td ng-style="{'background-color': x.color1}">{{x.property3}}</td>
    <td ng-style="{'background-color': x.color2}">{{x.property4}}</td>
</tr>

DEMO:演示:

 var app = angular.module('app', []); app.controller('tableController', function($scope) { $scope.response = [{ property1: 'Jill', property2: 'Smith', color1: 'red', color2: 'green' }, { property1: 'John', property2: 'Doe', color1: 'yellow', color2: '#336699' }, ]; });
 table, td { border: 1px solid black; border-collapse: collapse; } td {padding: 10px; min-width:120px;}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <table ng-controller="tableController" ng-app="app"> <tr ng-repeat="x in response"> <td ng-style="{'background-color': x.color1}">{{x.property1}}</td> <td ng-style="{'background-color': x.color2}">{{x.property2}}</td> </tr> </table>

Use ng-style to change background color, With this you can bind any css style.使用ng-style改变背景颜色,这样你就可以绑定任何 css 样式。 please find documentation here: https://docs.angularjs.org/api/ng/directive/ngStyle请在此处找到文档: https : //docs.angularjs.org/api/ng/directive/ngStyle

<tr ng-repeat="x in response">
  <td>{{x.property1}}</td>
  <td>{{x.property2}}</td>
  <td ng-style="{'background-color': x.color1}">{{x.property3}}</td>
  <td ng-style="{'background-color': x.color2}">{{x.property4}}</td>
</tr>

Please find the example below of how can you use ng-style to set styles dynamically.请在下面找到如何使用ng-style动态设置样式的示例。

 var app = angular.module('app', []); app.controller('ctrl', function($scope) { $scope.myName = { name: 'Dummy name', color1: 'white', color2: 'tomato', }; });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <div ng-controller="ctrl" ng-app="app"> <p ng-style="{'background-color': myName.color2, 'color': myName.color1}"> {{ myName.name }} </p> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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