Dariel Pratama
Dariel Pratama

Reputation: 1675

angular change class by id

I have collection in angular. the collection looks like:

$scope.collection = [{id:'a1', title:'title 1'}, {id:'a2', title:'title 2'}];
<span ng-repeat="c in collection" id="{{c.id}}">{{c.title}}</span>

it is then itterate using ngRepeat in a span tag. in other line i have buttons that have custom property, let say data-span-id, like so:

<button type="button" data-span-id="a1">
<button type="button" data-span-id="a2">

when that buttons clicked, i want to change the class of the span that have id equal to data-span-id property. in jQuery

$('#'+$(this).data('span-id')).addClass('someclass');

how to this in angular? PS: spans and buttons is scallable.

Upvotes: 0

Views: 811

Answers (1)

James Gaunt
James Gaunt

Reputation: 14783

It's hard to answer without seeing more of your code, but something along these lines is how I'd do it....

<button ng-repeat="item in collection" ng-click="selected = item.id">{{ item.title }}</button>

<span ng-repeat="item in collection"  ng-class="{ 'someClass': selected == item.id }">{{ item.title }}</span>

So clicking a button sets a variable in the scope to the id you want, and then your span checks for that variable to set a class.

Upvotes: 3

Related Questions