在 angularjs 中隐藏有关文本焦点的错误消息

Hide error message on text focus in angularjs

我是 angularjs 的初学者。我刚开始进行表单验证。一切正常,直到我试图隐藏输入焦点上的错误消息。

当我点击提交按钮时,它显示错误消息。在我关注文本框后,它必须隐藏错误消息

这是我的代码:

  <form name="form" novalidate>
        <div>
            <label>Username</label>
            <input type="text" name="username" ng-model="username" ng-required="true" ng-minlength="5" ng-maxlength="7"/>

            <span class="errors" ng-show="(form.$submitted || form.username.$touched) && form.username.$error.required">Please fill username</span>
            <span class="errors" ng-show="form.username.$error.minlength">Username too short</span>
            <span class="errors" ng-show="form.username.$error.maxlength">Username too long</span>
        </div>
  </form>

请有人帮助我

我猜你忘了提到 ng-app 指令

这只是一个技巧,试试看是否有效:

<form name="form" novalidate>
    <div>
        <label>Username</label>
        <input type="text" name="username" ng-model="username" ng-required="true" ng-minlength="5" ng-maxlength="7" ng-focus="focused=true"/>

        <span class="errors" ng-show="(form.$submitted || form.username.$touched) && form.username.$error.required && !focused">Please fill username</span>
        <span class="errors" ng-show="form.username.$error.minlength && !focused">Username too short</span>
        <span class="errors" ng-show="form.username.$error.maxlength && !focused">Username too long</span>
    </div>
</form>

注意:点击提交时,使 focused = false;

使用 ng blur 在刚离开输入字段时显示即时消息:

<form name="form" novalidate>
    <div>
        <label>Username</label>
        <input type="text" name="username" ng-model="username" ng-required ng-minlength="5" ng-maxlength="7" ng-blur="focused=false" ng-focus="focused=true"/>

        <span class="errors" ng-show="(form.$submitted || form.username.$touched) && form.username.$error.required && !focused">Please fill username</span>
        <span class="errors" ng-show="form.username.$error.minlength && !focused">Username too short</span>
        <span class="errors" ng-show="form.username.$error.maxlength && !focused">Username too long</span>
    </div>
</form>