Neil
Neil

Reputation: 2902

How to add/remove a class to the parent element of a checkbox on change in Angular js

I have a list with checkbox items in it, On selecting the checkbox I want to add a class to the parent li. How can I achieve this.

I am new to Angular.

<ul>
 <li><input type="checkbox" name="fruits[]" value="1">Apple</li>
 <li class="active"><input type="checkbox" name="fruits[]" value="2" checked>Orange</li>
 <li><input type="checkbox" name="fruits[]" value="3">Pear</li>

</ul>

On selecting the checkbox I want to add the class active to the parent li

Upvotes: 2

Views: 4441

Answers (1)

Davin Tryon
Davin Tryon

Reputation: 67296

You can do this with ng-class:

<ul>
 <li ng-class="{active: orange}"><input type="checkbox" ng-model="orange" name="fruits[]" value="2" checked>Orange</li>
</ul>

The {active: orange} is saying, "only add the active class if orange is truthy."

ng-model two-way binds the value of the checkbox. This gives you a variable orange to use inside the angular context.

Upvotes: 5

Related Questions