在ng repeat中按条件设置格式/样式

Conditionally format/style inside ng-repeat

本文关键字:设置 格式 样式 条件 ng repeat      更新时间:2023-09-26

我正试图想出一种方法,用AngularJS控制器的结果有条件地格式化html表(简单的背景色)。这将有望在ng repeat的迭代过程中发生,因为它在数组中的元素中工作。

我想实现的是:每当控制器内的函数返回true时,背景或样式都是绿色的,而当不是时,它将是红色的

在插入点的注释中查找"开始问题"。

        <!-- PLAYER STATS TABLE -->
    <div id = "StatsListTable">
    <table border="1" style="width:80%">
    <tr> <!-- TODO: class="tr.pstats" -->
        <th>Character Name</th>
        <th>    
            <div ng-app="KIdash" ng-controller="controller">
            Total Matches: {{TotalMatchesFunc()}} :: {{GreaterWins()}}
            </div>
        </th>
        <th class="green">Wins</th>
        <th class="red">Losses</th>
    </tr>
        <tr ng-repeat="ps in PlayerStats" class = "playerStatTable">
            <td>{{ps.name}}</td>
            <td>{{ps.matches}}</td>
            <!-- BEGIN QUESTION -->
            <!-- IF  {{GreaterWins()}}  make it green -->
            <!-- ELSE                   make it red   -->
            <script type="text/javascript">
            function() {
                if( controller.GreaterWins() )
                {
                    <th class="green">{{ps.wins}}</th>
                } else {
                    <th class="red">{{ps.wins}}</th>
                }
            }
            </script>
            <!-- END IF -->
            <td>{{ps.losses}}</td>
        </tr>
    <table>
    </div>
    <!-- END PLAYER STATS TABLE -->

您可以通过ng类来实现这一点。如下所示:

<tr ng-repeat="ps in PlayerStats" class = "playerStatTable">
      <td>{{ps.name}}</td>
      <td>{{ps.matches}}</td>
      <td ng-class="{'green': GreaterWins(),'red': !GreaterWins() }">{{ps.wins}}</td>                
      <td>{{ps.losses}}</td>
</tr>