使用ngMessages和ngShow闪烁

时间:2016-04-25 11:57:44

标签: html angularjs flicker ng-show ng-messages

在包含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>

1 个答案:

答案 0 :(得分:1)

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