matthewpavkov
matthewpavkov

Reputation: 2928

How to add checked class to a radio button in AngularJS

In AngularJS, I'm trying to add/remove a checked class on a parent element, when its child radio button is checked/unchecked.

<label ng-class="{checked: menuType.isChecked0}">
    <input type="radio" name="menuType" ng-model="menuType.isChecked0" />Text 1
</label>
<label ng-class="{checked: menuType.isChecked1}">
    <input type="radio" name="menuType" ng-model="menuType.isChecked1" />Text 2
</label>

Here is a fiddle: http://jsfiddle.net/fAA2w/

There is no controller or any other relative code. If there is a better way to approach this, please share. This seems simple enough, but I cannot find an answer to this question. What am I doing wrong here?

Upvotes: 3

Views: 11623

Answers (2)

Steve Farthing
Steve Farthing

Reputation: 792

You need to give the radio input a value.

For more examples see http://docs.angularjs.org/api/ng/input/input%5Bradio%5D.

<div ng-app>
<label ng-class="{checked: isChecked == 1}">
    <input type="radio" name="menuType" ng-model="isChecked" value="1" />Text 1
</label>

<label ng-class="{checked: isChecked == 2}">
    <input type="radio" name="menuType" ng-model="isChecked"  value= "2" />Text 
</label>
</div>

Upvotes: 15

tymeJV
tymeJV

Reputation: 104785

This is the correct way to be doing it. Reason being, when your ng-model changes, your ng-class will pick up on that and update the view, the Angular way!

Upvotes: 0

Related Questions