Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ng-repeat and ng-class on rows inside a table

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?

like image 468
oeoeaio Avatar asked Mar 14 '13 13:03

oeoeaio


People also ask

How do you use two ng-repeat in a table?

You can nest two ng-repeat together in order to create a more complex table. The first ng-repeat in the tr tag will create the rows and the second one in the td tag will create one column per element in the collection.

How do I get an index in NG-repeat?

Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.

What is data ng-repeat?

The data-ng-repeat allows the HTML to be validated through validators that do not understand Angular. The documentation is here with directives. This is from the docs: Angular normalizes an element's tag and attribute name to determine which elements match which directives.


2 Answers

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/

like image 68
jncraton Avatar answered Sep 28 '22 02:09

jncraton


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

like image 44
Jason Aden Avatar answered Sep 28 '22 03:09

Jason Aden