14

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.

6
  • simply add somthing like ng-class="{'yourClass': $index > friends.length / 2}" on the li. Commented Aug 27, 2013 at 14:34
  • 2
    that looks like black magic , are you sure it will work? Commented Aug 27, 2013 at 14:35
  • 1
    yes I'm pretty sure ;) If the logic is subject to change, you could of course extract it from the view and let the controller decide. Eg: ng-class="someConrollerMethod($index, friends)" Commented Aug 27, 2013 at 14:35
  • @Yoshi, you should create an answer. Perhaps a jsfiddle too. Commented Aug 27, 2013 at 14:42
  • 1
    i little bit shorter: ng-class="{'class-name': $index > $middle}" Commented Aug 27, 2013 at 14:45

1 Answer 1

29

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
  };
};
Sign up to request clarification or add additional context in comments.

1 Comment

I found that "special" had to be in quotes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.