Reputation: 91
I'm trying to bind a button inside ng-repeat
to that unique element for the button within the same repeat, pretty hard to word for me so I'll give a code snippet.
<li ng-repeat="thing in listOfThings track by $index">
<div ng-model="text"> text < /div>
<button ng-click="highlightText()" />
</ li>
Although not exact, that's the idea. The problem is that when I click the button, it will highlight all the texts inside the listOfThings
.
Note: assume that the text is given a ng-class that highlights when a boolean is true, and not highlighted when it's false, toggled by the button.
Any idea how to "bind" that button to only that one text so it doesn't highlight everything else?
I've tried to google for it, it might be a duplicate question but not sure how to search for something this specific so please link the answer if it's a duplicate.
Upvotes: 0
Views: 79
Reputation: 21
If I understand your example correctly, your ng-class
is going to apply the class to all items inside of your repeat based on the click event.
You need to track the button selection individually, by each element in the list. Something like:
HTML:
<li data-ng-repeat="thing in listOfThings track by $index">
<div data-ng-model="text" data-ng-class="{ 'highlighted': thing.Selected }"> < /div>
<button data-ng-click="highlightText(thing)" />
</li>
JS:
$scope.highlightText = function(thing){
thing.Selected = true;
}
CSS:
.highlighted{
background-color: yellow;
}
EDIT: Good suggestion made by skyboyer, this could be made cleaner by moving the highlighted function and not tracking the flag on the thing
variable.
HTML:
<li data-ng-repeat="thing in listOfThings track by $index">
<div data-ng-model="text" data-ng-class="{ 'highlighted': selected }"> < /div>
<button data-ng-click="selected = true" />
</li>
Upvotes: 1