角度单选按钮在 ng值更改时取消选择

Angular Radio Button Deselects when NgValue Changes

本文关键字:取消 选择 单选按钮 ng      更新时间:2023-09-26

我在表单中有一组必需的单选按钮。其中一个单选按钮具有键入自定义值的选项。如果我选择此单选按钮并开始键入自定义值,则会取消选择单选按钮。我该如何解决这个问题?

<div ng-controller="MyCtrl">
    <form>
        <input type="radio" value="red" ng-model="color" ng-required="!color">red</input>
        <input type="radio" value="blue" ng-model="color" ng-required="!color">blue</input>
        <input type="radio" ng-value="field" ng-model="color" ng-required="!color">Other:</input>
        <input type="text" ng-model="field"></input>
    </form>
</div>

在这里杰斯菲德尔。

如输入型无线电的 AngularJS 官方文档中所述

ngValue :角度表达式,用于设置选择时应将表达式设置为的值。

因此,一旦更改在 ngValue 属性中分配的模态变量,它就会自动取消选择单选按钮,这样,当再次选择它时,分配给 ngValue 的表达式中的值可以分配给单选按钮。

因此,您可以监视文本框中的更改,并在每次按键命中时设置模态变量的值。

.HTML:

    <input type="radio" value="{{field}}" ng-model="color" ng-required="!color">Other:</input>
    <input  ng-change="checkState()" type="text" ng-model="field"></input>

.JS:

    $scope.checkState = function() {
        $scope.color = $scope.field;
    };

更新了此处的普伦克