我有一个带有选择的 Angular 表单,该表单被标记为必需。
加载表单时,会显示“选择区域”消息,提示用户进行选择。
但是,即使该表单没有有效的选择,它也是有效的。
如果用户选择有效选项,然后选择“选择区域”,则表单验证会将表单标记为无效。
为什么表格一开始就不是无效的?
代码:
<div ng-controller="MyCtrl">
<form name="myForm">
<select name="region"
ng-model="regionId"
ng-options="region.id as region.name for region in regions"
ng-selected="region.id"
required>
<option value="">-- choose a region --</option>
</select>
</form>
</div>
Run Code Online (Sandbox Code Playgroud)
控制器:
function MyCtrl($scope) {
var myRegions = [{ id: 1, name: "England" },
{ id: 2, name: "Wales" },
{ id: 3, name: "Northern Ireland" },
{ id: 4, name: "Scotland" }
];
$scope.regions = myRegions;
$scope.regionId = 0;
}
Run Code Online (Sandbox Code Playgroud)
这是jsfiddle中的代码。
您的表单有效,因为您设置了初始值$scope.regionId = 0;。只需将其删除或更换即可$scope.regionId = "";。
jsfiddle上的实例。
angular.module('ExampleApp', [])
.controller('ExampleController', function() {
var vm = this;
var myRegions = [{
id: 1,
name: "England"
}, {
id: 2,
name: "Wales"
}, {
id: 3,
name: "Northern Ireland"
}, {
id: 4,
name: "Scotland"
}];
vm.regions = myRegions;
vm.regionId = "";
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
<div ng-controller="ExampleController as vm">
<form name="myForm">
isValid: {{myForm.$valid}}
<br>
<select name="region" ng-model="vm.regionId" ng-options="region.id as region.name for region in vm.regions" ng-selected="vm.region.id" required>
<option value="">-- choose a region --</option>
</select>
</form>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3880 次 |
| 最近记录: |