60

I am using AngularJS and the effect I want to get would be something similar to what this would produce, assuming it would work (which it doesn't).

View

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

Controller

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

I realise that this code won't work because person is unavailable to ng-class as it will only be available to objects inside each row. The code is to get the idea of what I'm trying to do across: ie. I want to be able to have table rows that are created using ng-repeat whose class is also based on a condition which depends on access to the scoped feature of row itself eg. person. I realise I could just add ng-class on the columns but that is boring. Anyone have any better ideas?

jncraton
  • 9,022
  • 3
  • 34
  • 49
oeoeaio
  • 685
  • 1
  • 6
  • 6
  • possible duplicate of [How do I conditionally apply CSS styles in AngularJS?](http://stackoverflow.com/questions/13813254/how-do-i-conditionally-apply-css-styles-in-angularjs) – gion_13 Mar 14 '13 at 17:55

3 Answers3

65

This should actually work fine. Person should be available on the tr element as well as on its children since they share the same scope.

This seems to work fine for me:

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

http://jsfiddle.net/xEyJZ/

jncraton
  • 9,022
  • 3
  • 34
  • 49
8

Actually, you can use "person" in the context you are referring to. It exists on the item being repeated as well as any items within it. The reason is that any directives on a particular element share the same $scope object. ng-repeat has a Priority of 1000, so it has already created its $scope and put "person" into it, therefore "person" is available to ng-class.

See this Plnkr:

http://plnkr.co/edit/ZI5Pv24U01S9dNoDulh6

Jason Aden
  • 2,823
  • 1
  • 18
  • 13
0

Normally I like to give a more comprehensive answer but there is too much code involved in this bit to do that. So will just show what is most important and hope anyone looking at this knows how use it. My dynamic JSON array has both columns and rows in it but the main thing that matters for this bit is ng-show="$last". This should only show the last row in the dynamic JSON array.

<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>
Deathstalker
  • 794
  • 10
  • 8