使用 ngMessages 和 ngShow 闪烁

Flicker with ngMessages and ngShow

在具有 required-验证和 ng-messages 的表单上,我使用 ng-show 在启动时隐藏指令,并且仅在输入 ng-dirty 后显示错误消息。

为了在布局中保持元素填充 space,我遵循 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>

 <ng-messages ng-show="user_form.name.$dirty && !user_form.name.$valid" for="user_form.name.$error">