在表格内的行上使用ng-repeat和ng-class

时间:2013-03-14 13:28:58

标签: angularjs angularjs-ng-repeat

我正在使用AngularJS,我希望获得的效果类似于它会产生的效果,假设它可以工作(它没有)。

查看

<tr ng-repeat='person in people' ng-class='rowClass(person)'>
  <td>.....info about person...</td>
  <td>.....info about person...</td>
  <td>.....info about person...</td>
</tr>

控制器

$scope.rowClass = function(person){
  ...return some value based upon some property of person...
}

我意识到此代码无效,因为person ng-class不可用,因为它只能用于每行内的对象。代码是为了了解我正在尝试做的事情:即。我希望能够拥有使用ng-repeat创建的表行,其类也基于一个条件,该条件依赖于对行本身的范围特征的访问,例如。 person。我意识到我可以只在列上添加ng-class,但这很无聊。谁有更好的想法?

3 个答案:

答案 0 :(得分:66)

这实际上应该可以正常工作。人员应该在tr元素及其子元素上可用,因为它们具有相同的范围。

这似乎对我很好:

<table>
    <tr ng-repeat="person in people" ng-class="rowClass(person)">
        <td>{{ person.name }}</td>
    </tr>
</table>

http://jsfiddle.net/xEyJZ/

答案 1 :(得分:8)

实际上,您可以在您所指的上下文中使用“person”。它存在于重复的项目以及其中的任何项目中。原因是特定元素上的任何指令共享相同的$ scope对象。 ng-repeat的优先级为1000,因此它已经创建了$ scope并将“person”放入其中,因此“person”可用于ng-class。

见Plnkr:

http://plnkr.co/edit/ZI5Pv24U01S9dNoDulh6

答案 2 :(得分:0)

通常情况下,我想提供更全面的答案,但这一点涉及的代码太多了。所以只会展示最重要的东西,希望看到这个的人知道如何使用它。我的动态JSON数组中包含列和行,但对于这一点而言最重要的是ng-show =&#34; $ last&#34;。这应该只显示动态JSON数组中的最后一行。

<tr ng-repeat="row in table.rows" ng-show="$last">

   <td ng-repeat="column in table.cols" ng-show="column.visible == true" nowrap >{{row[column.columnname]}}</td>
</tr>
相关问题