将ngClass应用于声明ngRepeat的元素

时间:2014-10-16 13:07:09

标签: javascript html arrays angularjs

我有一个表格,其中使用AngularJS ngRpeat生成行:

<tr ng-repeat="player in division">
  <td>{{player.name}}</td>
  <td>{{player.score}}</td>
</tr>

数组看起来有点像这样:

$scope.divison = [
  {
    name: "John Doe",
    score: "10",
    goingUp : true
  },
  {
    name: "Bob Marley",
    score: "20"
  }
];

现在,如果我想根据特定ng-classng-repeat应用于表格行,该怎么办?我会这样做可能会有效:

<tr ng-repeat="player in division" ng-class="'goingUp' : player.goingUp">
  <td>{{player.name}}</td>
  <td>{{player.score}}</td>
</tr>

唉,这不起作用。可能是因为ng-class并不在重复元素中。我怎么能让这个工作呢?

2 个答案:

答案 0 :(得分:1)

正确的语法是

ng-class="{'goingUp' : player.goingUp}"

答案 1 :(得分:0)

应该可以像this案例那样这样做。您可以将函数写入控制器范围,返回适当的类:

$scope.isGoingUp = function(player)
{
  if (player.goingUp) return "goingUp";
  return "notGoingUp";
}

然后像这样调用它

ng-class="isGoingUp(player)"