Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Setting Class In Ng-Repeat

I am creating a list in an ng-repeat , I need to give all li elements who are the nth child of their father or more , a certain class (in our ng-repeat it means all children who have an index greater than middle) . For example , if the list is 10 items I need to give the 5th,6th...10th li children a class . So if my code is something this -

 [ul]
    [li  ng-repeat="friend in friends"]
       {{friend.name}} who is {{friend.age}} years old.
    [/li]
  [/ul]

What is a possible and good way to assign a class to the children from the middle index and above? My conditions are that I shouldn't change the structure of the html . I can add directives\filters or add things to controllers.

like image 432
Joel Blum Avatar asked Aug 27 '13 14:08

Joel Blum


1 Answers

simply use ng-class on the repeated element, eg:

<li
  ng-repeat="friend in friends"
  ng-class="{special: $index > friends.length / 2 - 1}">

  {{friend.name}}
</li>

demo: http://jsbin.com/iFigAYi/1/


or extract the logic, like:

<ul>
  <li ng-repeat="friend in friends" ng-class="getClass($index, friends)">
    {{friend.name}}
  </li>
</ul>

and

$scope.getClass = function getClass(idx, list) {
  return {
    special: idx > list.length / 2 - 1
  };
};
like image 134
Yoshi Avatar answered Oct 11 '22 18:10

Yoshi