simeg
simeg

Reputation: 1879

AngularJS - Select dynamic ng-repeat DOM element in directive

Problem:
I have a directive which has a list <ul> and dynamically generated list items <li>s. I want to change the css of one of these <li> items.

Here's the code the for the template attribute of the directive:

<ul>
    <li ng-repeat="color in colors" ng-class="{selected: (color===selected) }" ng-click="pick(color)" style="background-color:{{color}};"></li>
</ul>

I want to change the css of the third element, that is $first + 2, but I don't know how to access it.

What I've tried
1) Since I want the directive to work without jQuery I've been trying with angular.element (which is jqLite). I can access the <ul> by angular.element.find('li') or just element.children() inside the link of the directive but I can't seem to get "further down" than that, because they are dynamically created (I guess).

2) I've been trying to access it through $first+2 and adding a css class to it in the ng-repeat like this:

<ul>
    <li ... ng-class="{ ... , cssClass: ($first+2) }" ...></li>
</ul>

But then all <li> elements are affected.

Here's a working plunker

Upvotes: 0

Views: 704

Answers (1)

charlietfl
charlietfl

Reputation: 171679

Can use $index

<li ng-class="{ cssClass: $index == 2 }"></li>

Upvotes: 1

Related Questions