我想用 required 验证下拉列表。仅当值为 null 或空白时才需要默认值(如果我错了,请纠正我)。如果值是“未分配”,我希望需要给出错误并使表单无效。
<select name="first" class="select" title="Select Approver" ng-model="applications.first" ng-options="x.id as x.value for x in list1" ng-change="SetToAll(applications.first,'1')" required></select>
使用它我可以显示错误消息,但这确实使表单无效
<span class="error" ng-show="applications.first == 'not assigned'?true:false">Select Approver</span>
解决方案:-
1)如果你想使用required然后检查Shannon Hochkins解决方案。
<form name="formName">
<select name="first" class="select" title="Select Approver" ng-model="applications.first" ng-options="x.id as x.value for x in list1" ng-change="SetToAll(applications.first,'1')" required="true">
<option value="">Not Assigned</option>
</select>
<span class="error" ng-show="formName.first.$invalid ?true:false">Select Approver</span>
<pre>{{formName | json}}</pre>
</form>
他添加了一个带有空白值的选项<option value="">Not Assigned</option>
。并required="true"
在选择中设置。这完美地工作。
2)使用自定义指令。
app.directive('req', [
function() {
var link = function($scope, $element, $attrs, ctrl) {
var validate = function(viewValue) {
var comparisonModel = $attrs.req;
var invalid = $attrs.invalid;
if (viewValue == invalid) {
// It's valid because we have nothing to compare against
ctrl.$setValidity('req', false);
} else {
ctrl.$setValidity('req', true);
}
};
$attrs.$observe('req', function(comparisonModel) {
// Whenever the comparison model changes we'll re-validate
return validate(ctrl.$viewValue);
});
};
return {
require: 'ngModel',
link: link
};
}
]);
和你的 html 代码:
<select invalid="not assigned" req={{applications.first}} name="first" class="select" ng-model="applications.first" ng-options="x.id as x.value for x in list1" title="Select Approver" ></select>
<span class="error" ng-show="Step5.first.$error.req">Select Approver</span>
在这里,您必须设置invalid="not assigned"
或任何值,如invalid='0'
or invalid=' '
。在指令中,如果值匹配,它将与无效属性进行比较,它将显示错误。