【问题标题】:Conditionally format/style inside ng-repeat在 ng-repeat 中有条件地格式化/样式
【发布时间】:2016-03-24 21:42:39
【问题描述】:

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

我想要完成的是:每当控制器内的函数返回true时,背景或样式为绿色,否则为红色。

在插入点的评论中查找“BEGIN QUESTION”。

        <!-- 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 -->

【问题讨论】:

  • 为什么要更新原来的问题?如果您愿意,我会说保留原始问题并添加解决方案的编辑。

标签: javascript html angularjs


【解决方案1】:

你可以通过 ng-class 来做到这一点。如下所示:

<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>

【讨论】:

  • 多么棒的答案!感谢您。我所有的结果都是红色的,我需要做些什么来保证 GreaterWins() 函数实际上被正确使用了吗?在这种情况下,我是否需要将其称为 controller.GreaterWins()?
  • 您不需要显式编写controller.GreaterWins(),因为您没有使用控制器作为语法。 GreaterWins() 函数是否定义在 controller 范围内?它总是返回false吗?
  • 当我用 T 或 F 替换逻辑 > 比较时,它的行为符合预期。所以看来我只是没有正确比较这些值。
  • 哦!我需要将 ng-repeat $index 发送到 GreaterWins() 函数以获取我的数组的正确索引。使用 ng-class 时可以这样做吗?
  • 是的,你可以这样做 &lt;td ng-class="{'green': GreaterWins($index),'red': !GreaterWins($index) }"&gt;{{ps.wins}}&lt;/td&gt; 或者你甚至可以直接传递实际元素而不是像 &lt;td ng-class="{'green': GreaterWins(ps),'red': !GreaterWins(ps) }"&gt;{{ps.wins}}&lt;/td&gt; 这样的索引
猜你喜欢
  • 1970-01-01
  • 2013-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-10
  • 2014-02-24
相关资源
最近更新 更多