AngularJS将单选按钮绑定到跨多个对象的布尔值

时间:2015-02-25 16:21:35

标签: angularjs

我正在尝试将对象数组绑定到单选按钮组的集合。我已经达到了基于模型生成组并基于布尔值selected预先选择正确的单选按钮的程度,但我无法弄清楚如何将绑定项的值切换为true和单选按钮值更改时为false。基本上,我希望这些功能像互斥复选框一样。我可以用实际的复选框来做这件事,但显然单选按钮是理想的,因为这是他们的预期用途。

JSFiddle为方便起见:http://jsfiddle.net/uv9mwkwd/5/

HTML:

<div ng-app ng-controller="Extensions">
    <div ng-repeat="propertyGroup in propertyGroups">
        {{propertyGroup.label}}
        <div ng-repeat="prop in propertyGroup.properties">
            <input type="radio" ng-model="prop.selected" name="prop{{propertyGroup.alias}}" ng-value="true" /> {{prop.value}}
        </div>
    </div>
</div>

脚本:

function Extensions($scope) {
  $scope.propertyGroups = [
    {'label': 'Property 1',
     'alias': 'property1',
     'properties': [{value: 'Value 1', selected: true},{value: 'Value 2', selected: false}]},
    {'label': 'Property 2',
     'alias': 'property2',
     'properties': [{value: 'Value 1', selected: false},{value: 'Value 2', selected: true}]}
  ];
    console.debug($scope.propertyGroups);
}

1 个答案:

答案 0 :(得分:1)

问题是您正在尝试将“已选择”值分别连接到每个单选按钮。相反,请将其放在模型的propertyGroup部分中。

jsFiddle example

$scope.propertyGroups = [
    { label : 'Property 1',
      alias : 'property1',
      selected : 'Value 1', // <---------- this stores which value is checked
      properties: [{value: 'Value 1'},{value: 'Value 2'}]},
    { label : 'Property 2',
      alias : 'property2',
      selected : 'Value 2', // <---------- this stores which value is checked
      properties : [{value: 'Value 1'},{value: 'Value 2'}]}

];

在您的HTML中,请注意您的ng-model正在查看单选按钮的整体group以匹配“值”

   <div ng-repeat="prop in propertyGroup.properties">

        {{ propertyGroup.selected }} 
        <!-- ^ this is just so you can see it change the model-->

        <input type="radio" 
               ng-model="propertyGroup.selected" 
               name="prop{{propertyGroup.alias}}" 
               ng-value="prop.value" /> {{prop.value}}
    </div>