0

I have a very simple form where I have Yes and No radio buttons. Each radio button is bound to the same item in the scope (I am using AngularJS). The Yes button's value gets set to true on being selected and the No button's value gets set to false when being selected.

When I click the Yes button once, both the model and the html element changes correctly. But when I click the No radio button, the model changes correctly but the html element does not become selected. If I click the No radio button again the html element then changes to it's correct selected state.

The example below is just part of a larger html page and controller but I have kept the Angular model structure the same because this may be where the issue is.

HTML:

<div ng-app="myApp">
  <div ng-conroller="MyController">
    <div>
                <label>
                    <input type="radio" name="IsBeingPaid" ng-model="item.isBeingPaid" ng-checked="item.isBeingPaid" value="true"/>
                    Yes
                </label>
            </div>
            <div class="radio">
                <label>
                    <input type="radio" name="IsBeingPaid" ng-model="item.isBeingPaid" ng-checked="!item.isBeingPaid" value="false"/>
                    No 
                </label>
                <p>{{item.isBeingPaid}}</p>
            </div>
  </div>
</div>

Controller:

var app = angular.module('myApp', [
  'my.controllers'
]);

var controllers = angular.module('my.controllers', []);
controllers.controller('MyController', function($scope) {
    $scope.item = {};
});

I have created this fiddle to demonstrate the issue.

http://jsfiddle.net/prajna78/Tdq9n/14/

What am I missing? It seems like such a simple thing.

2

1 Answer 1

9

There are a few problems with your code.

First, use ng-value instead of value in your radio button elements. This makes sure that the value you're binding to is a boolean (true) and not a string ("true"). Also, you don't need ng-checked (ng-model is sufficient).

<input type="radio" name="IsBeingPaidMinimumWage" ng-model="isBeingPaidMinimumWage" ng-value="true"/>

Also, you're binding to item.isBeingPaidMinimumWage, but your $scope variable is just isBeingPaidMinimumWage, so the initial value that you assign in your controller isn't reflected in the view.

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Jerrad. The ng-value fixed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.