具有不同ng模型的单选按钮

时间:2017-03-22 13:02:23

标签: javascript angularjs radio-button

您好我有三个同名但不同ng模型的无线电输入字段:

<label>
    <input type="radio"name="deliveryAddress" 
           ng-model="CC.OrderDetailsModel.IsNewDeliveryAddress">
    Save address to profile for use on future orders
</label>

<label>
    <input type="radio"name="deliveryAddress" 
           ng-model="CC.OrderDetailsModel.ExistingDeliveryAddressUpdate">
    Update Existing Delivery Address
</label>

<label>
    <input type="radio"name="deliveryAddress" 
           ng-model="CC.OrderDetailsModel.UseForThisOrderOnly">
    Use address only for this order
</label>

我希望在输入检查时检查其值为true,否则为false

在这三个ng-model中,只有一个可以有true值。像这样:

CC.OrderDetailsModel.IsNewDeliveryAddress: false,
CC.OrderDetailsModel.ExistingDeliveryAddressUpdate: false,
CC.OrderDetailsModel.UseForThisOrderOnly: true

2 个答案:

答案 0 :(得分:1)

如果您explained in comments想要保留逻辑,可以在输入中添加ng-change事件来设置值:

<label>
   <input type="radio" name="deliveryAddress" 
          ng-model="CC.OrderDetailsModel.IsNewDeliveryAddress"
          ng-change="change(CC.OrderDetailsModel.IsNewDeliveryAddress)">
   Save address to profile for use on future orders
</label>

<label>
   <input type="radio" name="deliveryAddress" 
          ng-model="CC.OrderDetailsModel.ExistingDeliveryAddressUpdate"
          ng-change="change(CC.OrderDetailsModel.ExistingDeliveryAddressUpdate)">
   Update Existing Delivery Address
</label>

<label>
   <input type="radio" name="deliveryAddress" 
          ng-model="CC.OrderDetailsModel.UseForThisOrderOnly"
          ng-change="change(CC.OrderDetailsModel.UseForThisOrderOnly)">
   Use address only for this order
</label>

change()函数会将变量设置为false,然后将所选变量设置为true

$scope.change = function(changed) {
    CC.OrderDetailsModel.IsNewDeliveryAddress = false;
    CC.OrderDetailsModel.ExistingDeliveryAddressUpdate = false;
    CC.OrderDetailsModel.UseForThisOrderOnly = false;
    changed = true;
}

答案 1 :(得分:-1)

我建议您为所有单选按钮使用仅一个变量,如adviced by Angular for input[radio]

<input type="radio" name="deliveryAddress" ng-model="deliveryAddress" value="newDeliveryAddress"/>
<input type="radio" name="deliveryAddress" ng-model="deliveryAddress" value="existingDeliveryAddressUpdate"/>
<input type="radio" name="deliveryAddress" ng-model="deliveryAddress" value="useForThisOrderOnly"/>

这里只是更改ng-model中的value集。然后,您可以根据此值进行治疗。

Try it on Plunker