问题
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
回答1:
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">
回答2:
you can set the ng-model to the specified value you want in controller
$scope.radius.checked = $scope.radii[0]
回答3:
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
回答4:
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
来源:https://stackoverflow.com/questions/25389701/angular-js-ng-repeat-a-radio-button-list-from-scope-with-a-default-checked