我正在使用ng-messages
进行选择框验证,但我无法进行必要的验证。
我的代码有什么问题?
<form name="personalDetailForm" novalidate="">
<label class="item item-input" ng-class="{ 'has-errors' : personalDetailForm.title.$invalid, 'no-errors' : personalDetailForm.title.$valid}">
<span class="input-label">Title:</span>
<select data-ng-model="personalDetObj.title" ng-required="true" name="title">
<option value="">Select title</option>
<option value="Mr">Mr.</option>
<option value="Mrs">Mrs.</option>
</select>
</label>
<div class="error-container" ng-show="personalDetailForm.title.$dirty && personalDetailForm.title.$invalid" ng-messages="personalDetailForm.title.$error">
<div class="error" ng-message="required">
This field is required!
</div>
</div>
</form>
答案 0 :(得分:1)
负责显示消息的部分应更改为:
<div class="error-container"
ng-show="personalDetailForm.title.$dirty && personalDetailForm.title.$invalid"
ng-messages="personalDetailForm.title.$error">
<div class="error" ng-message="required">This field is required!</div>
</div>
注意正确使用ngMessages
,ngMessage
指令和personalDetailForm.title.$error
表达式(不是$errors
)。
angular.module('demo', ['ngMessages']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-messages.js"></script>
<form ng-app="demo" name="personalDetailForm" novalidate="">
<label class="item item-input" ng-class="{'has-errors' : personalDetailForm.title.$invalid, 'no-errors' : personalDetailForm.title.$valid}">
<span class="input-label">Title:</span>
<select data-ng-model="personalDetObj.title" ng-required="true" name="title">
<option value="">Select title</option>
<option value="Mr">Mr.</option>
<option value="Mrs">Mrs.</option>
</select>
</label>
<div class="error-container" ng-show="personalDetailForm.title.$dirty && personalDetailForm.title.$invalid" ng-messages="personalDetailForm.title.$error">
<div class="error" ng-message="required">This field is required!</div>
</div>
</form>