I'm using an angular directive and I am not having any luck with the jQlite .find() method:
DIRECTIVE
function cardsList () {
return {
restrict: 'A',
controller: 'CardsController',
templateUrl: 'app/directives/cards-list/cards-list.html',
link: function ($scope, $element, attr, CardsController) {
var cardLink = $element.find('a');
console.log(cardLink);
});
}
}
}
contextCards.directive('cardsList', cardsList);
An empty []
gets logged on the console.
TEMPLATE
<li data-ng-repeat="card in cards" class="cards--item">
<a class="cards--link" data-ng-href="#/{{ card.slug }}">{{ card.title }}</a>
</li>
VIEW
<ul class="col-xs-12 cards--list" cards-list></ul>
All I want to do is traverse to the <a>
elements. According to the docs, .find()
only works on tag names which is exactly what I'm trying to do.
EDIT: I want to add a class to the <a></a>
if the card the link represents is selected (like .current-card
)
From your answer it's not clear how the selected card is specified in the model, so I am assuming that the card
object (the object of each iteration of ng-repeat
) holds this flag, for example: card.isSelected
.
Then, you could use ng-class
to specify which CSS class to add based on this value:
<li ng-repeat="card in cards" class="cards--item">
<a class="cards--link"
ng-class="{'current-card': card.isSelected}"
ng-href="#/{{ card.slug }}">{{ card.title }}</a>
</li>
Addendum:
The answer to your original question about why .find("a")
returns empty, it is because ngRepeat
directive transcludes its content (which means that Angular takes the elements out of DOM during compilation), and places it at a later stage than your link
function.