从作用域中重复一个单选按钮列表,并选中默认值

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

本文关键字:列表 单选按钮 默认值 一个 作用域      更新时间:2023-09-26
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>

如何根据作用域半径的选中值设置默认单选按钮进行检查?在这种情况下,默认选中"2哩"。

砰砰作响:http://plnkr.co/edit/RP9SpO1qGjn5Ua6pZJ3D?p=preview

很简单。尽管angular文档中没有提到ng-checked,但它是可用的。

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

可以将ng-model设置为控制器

中的指定值
$scope.radius.checked = $scope.radii[0]

这里都很简单

ngModel保存一个模型(我们想要在其中存储选中的项目)
ngValue保存一个值(与此输入相关的项)

要访问我们想要的scope,我们应该从ngRepeat范围升级到$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

创建一个对象来保存选中的值,如:

美元范围。selectedValue = {id: 0

};

更新ng-model和value属性,如下所示:

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

参见工作示例:http://plnkr.co/edit/zpNItMx13YPH0guvod0D?p=preview