使用angualrjs 1.3
我的 ng-repeat 中有一个下拉菜单:
<tr ng-repeat="c in myData">
<td>
<select name="type" class="form-control" ng-model="c.type" required>
<option value="">--Select--</option>
<option ng-repeat="type in types">{{type.text}}</option>
</select>
</td>
</tr>
我如何对上述下拉列表进行必填字段验证。
我的 ng-repeat 中有其他文本框控件,我使用如下:
<td ng-class="{ 'has-error': myForm['comment_' + {{$index}}].$invalid && (myForm['comment__' + {{$index}}].$touched || myForm.$submitted) }">
<input type="text" name="comment_{{$index}}" required ng-model="c.comment" class="form-control" />
</td>
验证有效,但是当我尝试将相同的内容应用于下拉列表时,它不起作用。
有任何输入吗?
最佳答案
Angularjs 是一个大型且智能的库,您可以在其上执行所有操作,在示例中您可以使用 ng-form
和ng-options
和ng-required
而是使用常见的 html 代码并通过 $index
跟踪输入如本示例。
with
ng-form
you can define eachtr
as a form and then you can check form validation.
var app = angular.module("app", []);
app.controller("ctrl", function($scope) {
$scope.myData = [
{},{}
]
$scope.types = [1,2,3]
});
.has-error {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.20/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<table>
<tr ng-repeat="c in myData" ng-form="x">
<td>
<select ng-model="c.type" ng-options="option for option in types" ng-required="true"></select>
</td>
<td>
<input type="text" ng-model="c.text" ng-required="true" />
</td>
<td ng-class="{'has-error': x.$invalid}">
form is valid: {{x.$valid}}
</td>
</tr>
</table>
</div>
关于javascript - Angularjs:需要验证 ng-repeat 内的下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56007083/