Angularjs:文本字段只需要勾选单选按钮

Angularjs: Text field is only required of radio button is ticked.

本文关键字:单选按钮 文本 字段 Angularjs      更新时间:2023-09-26

我有一个单选按钮和一个文本字段。我希望只有在勾选单选按钮时才需要文本字段。

<label class="radio">
    <input type="radio" value="createNewCollection" ng-model="selectedCollection" />
</label>
<input type="text" ng-model="collectionName" placeholder="Create new Collection"/>

因此,只有在选择createNewCollection时,collectionName才是必需的。

angular.module('myApp', []);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form name="form" ng-app="myApp">
  <label class="radio">
    <input type="radio" value="createNewCollection" ng-model="selectedCollection">
  </label>
  <input type="text" name="input" ng-required="selectedCollection" ng-model="collectionName" placeholder="Create new Collection">
  <p ng-show="form.input.$error.required">This is required.</p>
</form>

您需要将该输入的ng-required属性设置为无线电输入的型号名称。ng-required="selectedCollection"

阅读此处的文档