webmandman
webmandman

Reputation: 317

angular js ng-repeat a radio button list from scope with a default checked

app.controller('radiusController', function($scope){
    $scope.radii = [
        {id:.25, checked:"false", name:"1/4 Mile"},
        {id:.5, checked:"false", name:"1/2 Mile"},
        {id:1, checked:"false", name:"1 Mile"},
        {id:2, checked:"true", name:"2 Mile"},
        {id:3, checked:"false", name:"3 Mile"},
        {id:4, checked:"false", name:"4 Mile"},
        {id:5, checked:"false", name:"5 Mile"}
    ];
    $scope.handleRadioClick = function(radius){
        window.radiochecked = radius.id;
    };
});

<li ng-repeat="radius in radii" id="selectradius-{{radius.id}}">

              <div class="radio">
                <label>

                  <input type="radio" name="radius"
                       ng-model="radius.checked"
                       ng-change="handleRadioClick(radius)">

                  {{radius.name}}

                </label>
              </div>

          </li>

How do I set the default radio button to be checked based on the checked value of scope radii? In this case the "2 Mile" should be checked by default.

plunker: http://plnkr.co/edit/RP9SpO1qGjn5Ua6pZJ3D?p=preview

Upvotes: 3

Views: 15918

Answers (4)

Sergio Espallargas
Sergio Espallargas

Reputation: 211

Create an object to hold the selected value, like:

$scope.selectedValue = { id: 0 };

Update ng-model and value attributes like shown below:

 <input type="radio" name="radius" ng-change="handleRadioClick()" 
          ng-model="selectedValue.id" value="{{radius.id}}">

See working sample: http://plnkr.co/edit/zpNItMx13YPH0guvod0D?p=preview

Upvotes: 0

vp_arth
vp_arth

Reputation: 14982

All simple here

ngModel holds a model(where we want store selected item)
ngValue holds a value(what item related to this input)

To access scope which we want, we should step up from ngRepeat scope with $parent.

<div ng-repeat="radius in radii">
      <label>
        <input type="radio" name="radius"
             ng-model="$parent.model"
             ng-value="radius" />
        {{radius.name}}
      </label>
</div>  

Plunkr

Upvotes: 0

webmandman
webmandman

Reputation: 317

Simple. Eventhough the angular docs do not mention ng-checked, it is available.

<input type="radio" name="radius"
                       ng-change="handleRadioClick(radius)"
                       ng-checked="radius.checked">

Upvotes: 4

user2165424
user2165424

Reputation:

you can set the ng-model to the specified value you want in controller

$scope.radius.checked = $scope.radii[0]

Upvotes: 0

Related Questions