【问题标题】:Conditionally change color of angularjs element?有条件地改变angularjs元素的颜色?
【发布时间】:2014-09-29 14:21:24
【问题描述】:

我对 AngularJS 还是很陌生。我正在尝试更改表格元素的颜色,以便在用户对此选项进行投票时将其变为黄色。

<div ng-show="poll.userVoted">
    <table class="result-table">
        <tr ng-repeat="choice in poll.choices">
            <td>{{choice.text}}</td>
            <td>
            <table ng-if="choice.text == poll.userChoice.text" style="background-color: yellow; width: {{choice.votes.length/poll.totalVotes*100}}%; text-align: right">
                <tr>

                        <td>{{choice.votes.length}}</td>
                </tr>
            </table>
            <table ng-if="choice.text != poll.userChoice.text" style="background-color: lightblue; width: {{choice.votes.length/poll.totalVotes*100}}%; text-align: right">
                <tr>

                    <td>{{choice.votes.length}}</td>
                </tr>
            </table>
            </td>
        </tr>
    </table>

【问题讨论】:

  • 如果我正确理解您的问题标题,您可以尝试这样的事情 - plnkr.co/edit/jeszGorMQmLiqhtWDt94?p=preview
  • 谢谢我会做这样的事情。我只是想我可以在标签中以某种方式做到这一点,而无需为其创建函数。

标签: css angularjs conditional


【解决方案1】:

这是通过使用 ng-class 完成的。

像这样在你的 td 上使用 ng-class:

<td ng-class="{yellowstyle: choice.text==poll.userChoice.text}">...</td>

当您的条件为真时,会将 css 类黄色样式放在项目上。

在你的例子中:

<table class="result-table">
  <tr ng-repeat="choice in poll.choices">
    <td>{{choice.text}}</td>
    <td>
      <table style="width: {{choice.votes.length/poll.totalVotes*100}}%; text-align: right">
        <tr>
          <td ng-class="{yellowstyle: choice.text==poll.userChoice.text, lightbluestyle: choice.text!=poll.userChoice.text}">{{choice.votes.length}}</td>
        </tr>
      </table>
    </td>
  </tr>
</table>

使用 style.css 文件:

.yellowstyle {background-color: yellow;}
.lightbluestyle {background-color: lightblue;}

【讨论】:

  • 这给了我一个语法错误:Error: Syntax Error: Token ':' is an unexpected token at column 12 of the expression [yellowstyle: choice.text==poll.userChoice.text, lightbluestyle: choice.text!=poll.userChoice.text] starting at [: choice.text==poll.userChoice.text, lightbluestyle: choice.text!=poll.userChoice.text].
  • 抱歉忘记了 ng-class 中的 {},已修复,重试
猜你喜欢
  • 2019-03-23
  • 2023-04-04
  • 1970-01-01
  • 2015-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-12
  • 2020-12-03
相关资源
最近更新 更多