AngularJS未选择必填下拉选单时myForm.$valid意外为true如何调试

我设置了一个保存按钮,仅当所有表单数据填写完整且表单valid(有效)时才会启用。我无法理解为何带宽选项尚未选择,表单就变为有效状态:myForm.$valid会切换为true,但它本应保持为false。
保存按钮代码:
<button id="save-create-account-modal" type="submit" class="btn btn-success" ng-disabled="!myForm.$valid || $ctrl.disableButton" ng-click="$ctrl.accessPointSave($ctrl.accessPoint)"> 保存 </button>
带宽选择菜单代码如下:
<div class="col-xs-3"> <div class="form-group" ng-class="{ 'has-error': myForm.uplink.$touched && myForm.uplink.$invalid }"> <label for="uplink" class="required"> <translate>GENERAL.UPLINK.value</translate> </label> <select id="edit-service-plan-uplink-select" class="form-control" name="uplink" ng-model="$ctrl.accessPoint.uplink" ng-options="bandwidth.value as bandwidth.option for bandwidth in $ctrl.uplinks" required> </select> </div> <span class="message error" ng-messages="myForm.uplink.$error" ng-if="myForm.uplink.$touched"> <p ng-message="required"> <translate>GENERAL.FORM_VALIDATIONS.REQUIRED_FIELD.value</translate> </p> </span> </div> <div class="col-xs-3"> <div class="form-group" ng-class="{ 'has-error': myForm.downlink.$touched && myForm.downlink.$invalid }"> <label for="downlink" class="required"> <translate>GENERAL.DOWNLINK.value</translate> </label> <select id="edit-service-plan-downlink-select" class="form-control" name="downlink" ng-model="$ctrl.accessPoint.downlink" ng-options="bandwidth.value as bandwidth.option for bandwidth in $ctrl.downlinks" required> </select> </div> <span class="message error" ng-messages="myForm.downlink.$error" ng-if="myForm.downlink.$touched"> <p ng-message="required"> <translate>GENERAL.FORM_VALIDATIONS.REQUIRED_FIELD.value</translate> </p> </span> </div>
我该如何进一步调试该问题?
更新
我也尝试过在<select>标签行添加required属性
仍然没有达到预期效果
排查解决方案
- 确认ng-model初始值是否异常:打开浏览器控制台打印
$ctrl.accessPoint.uplink和$ctrl.accessPoint.downlink的初始值,若初始值为非undefined的空值(如空字符串、0),AngularJS的required校验会认为字段已赋值,直接通过校验。将这两个字段的初始值设为undefined即可修复该问题。 - 强制添加空默认选项:在select标签内添加
<option value="">请选择</option>,要求用户必须选中非空值才能通过校验,规避初始值异常导致的校验失效。 - 打印表单校验状态定位问题:在页面临时添加调试代码输出
myForm.uplink.$error、myForm.downlink.$error、myForm.$error的实时值,确认是这两个下拉框的校验规则未生效,还是表单内其他字段的校验异常导致整体$valid状态误判。 - 检查表单嵌套结构:确认所有下拉框元素都在
<form name="myForm"></form>标签内部,若不在form范围内,下拉框的校验状态不会同步到myForm对象中,自然不会影响整体表单的有效性。 - 校验下拉选项数据源:确认
$ctrl.uplinks、$ctrl.downlinks数组内每个元素的value字段都不为空,避免选中后ng-model仍为空的情况。
内容的提问来源于stack exchange,提问作者code-8
相关产品推荐
相关产品推荐

