Anish S.
Anish S.

Reputation: 63

Add class to selected ng-repeat list elements

Hey I'm looping thru an array using ng-repeat in my template. The list spits out 9 list elements and I would like change the background color of the selected list element but I want to do it in a way where multiple ones can be selected and the color of the selected ones with a different background color. Initially I had passed $event to the click function on the list element and added a class to event.target but that put the class on all the list elements rather than the selected one.

<ul>
            <li class="info-items"
                ng-repeat="card in config.cards"
                ng-class="{'error-border': emptyCardsArray}">
                <div class="inner-text"
                     ng-model="userSelection.cards"
                     ng-click="addCard(card.name, $event)">{{card.name}}{{$index + 1}}</div>
            </li>
        </ul>

HTML:

$(event.target).addClass('active.cards');

JS:

The list that I'm repeating thru unforunately doesn't have a unique ID or I would have passed in the ID and created a condition to check whether the selected items have one and applied the class.

Upvotes: 0

Views: 732

Answers (1)

Richard Hamilton
Richard Hamilton

Reputation: 26434

It's a much better practice to simply use ng-class for this.

<ul>
  <li class="info-items"
      ng-repeat="card in config.cards"
      ng-class="{'error-border': emptyCardsArray}">
      <div class="inner-text"
           ng-model="userSelection.cards"
           ng-class="active.cards">{{card.name}}{{$index + 1}}
      </div>
   </li>
</ul>

Upvotes: 0

Related Questions