在包含required
的表单上 - 验证和ng-messages
我使用ng-show
在启动时隐藏指令,并仅在输入ng-dirty
后显示错误消息。
为了让元素在布局中填充它的空间我遵循css规则来覆盖默认的ng-hide
行为:
ng-messages.ng-hide:not(.ng-hide-animate), [ng-messages].ng-hide:not(.ng-hide-animate)
{
display: block !important;
visibility: hidden;
}
当我现在在输入字段中输入文本时,错误消息很快就会显示,然后再次隐藏(由于填写了必填字段)。在表单验证完成之前,感觉ng-dirty
已经解决了,导致了这种行为。
参见 this Fiddle
或查看
代码:
var $scope;
var app = angular.module('myapp', ['ngMessages', 'ngAnimate']);
app.controller('UserCtrl', ['$scope', UserCtrl]);
function UserCtrl($scope) {
$scope.showField = true;
$scope.reset = function() {
var master = { name: '' };
$scope.temp = angular.copy(master);
$scope.user_form.$setPristine();
}
}
ng-messages.ng-hide:not(.ng-hide-animate), [ng-messages].ng-hide:not(.ng-hide-animate)
{
display: block !important;
visibility: hidden;
}
ng-messages, [ng-messages]
{
display: block;
height: 1em;
}
input
{
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-animate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-messages/1.5.5/angular-messages.min.js"></script>
<div ng-app="myapp">
<div ng-controller="UserCtrl">
<form name="user_form" novalidate>
<input name="name" ng-model="temp.name" ng-show="showField" placeholder="Name" required autocomplete="off"/>
<ng-messages ng-show="user_form.name.$dirty" for="user_form.name.$error">
<ng-message when="required">
Please enter your name
</ng-message>
</ng-messages>
<button type="button" class="button" ng-click="reset()">Reset</button>
</form>
<p>
Pristine: {{user_form.$pristine}}
</p>
<pre>Errors: {{user_form.$error | json}}</pre>
</div>
</div>
答案 0 :(得分:1)
<ng-messages ng-show="user_form.name.$dirty && !user_form.name.$valid" for="user_form.name.$error">