javascript - ngBlur 上的 Angular setPristine

标签 javascript angularjs validation

  • 我有一个带有密码字段的表单,我为其实现了一个password 指令。
  • 我目前只实现了 1 项验证,但我有一个现场验证列表。
  • 我希望它们分别显示为红色或绿色,具体取决于有效/无效 - 当用户开始在字段中输入时。如果用户控件开箱即用并且所有验证都通过,我想将该字段设置为有效并将其设置为原始状态,以便验证列表不会显示。
  • 但是,如果任何验证失败,我希望即使该字段不在焦点上也能看到所有验证。下面是我的表单组片段。

    <div class="form-group">
      <label for="inputPass" class="col-sm-3 control-label text-sm text-left">Password</label>
      <div class="col-sm-9">
        <input type="password" placeholder="Password" 
          class="form-control" ng-model="registerAccount.password" 
          required name="inputPass" id="inputPass" 
          password ng-blur="form.inputPass.$invalid ? return: form.inputPass.$setPristine">
        <div ng-show="form.inputPass.$dirty" class="help-block">
          <p class="text-danger" ng-show="form.inputPass.$error.required">
            Password is required.
          </p>
         <p ng-class="form.inputPass.$error.invalidLength ? 'text-danger' : 'text-success'">
            Password should be atleast 8 characters.
         </p>
       </div>
     </div>
    </div>
    

以下是我的指令

'use strict';

angular.module('nileLeApp')
.directive('password', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function ($scope, $element, $attrs, ngModelCtrl) {
            $scope.$watch($attrs.ngModel, function (value) {

                if (value) {
                    var length = (value.length >= 8);
                    ngModelCtrl.$setValidity('invalidLength', length);
                }

            });
        }
    };
});

当焦点离开字段时,验证列表仍然显示出来。我原以为它会被隐藏,因为该字段被设置为原始状态。有任何想法吗 ?我希望它类似于 https://dl.dropboxusercontent.com/u/636000/password_verification/index.html 中的密码字段.当用户键入密码时,验证以红色/绿色反射(reflect)。

最佳答案

您没有调用 $setPristine 方法。应该是 form.inputPass.$setPristine():

ng-blur="form.inputPass.$invalid ? return: form.inputPass.$setPristine()"

或更简洁的变体:

ng-blur="form.inputPass.$valid && form.inputPass.$setPristine()"

关于javascript - ngBlur 上的 Angular setPristine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34783849/

相关文章:

javascript - Angularjs 自定义指令范围 :true change it's parent scope

javascript - html 中是否有技巧可以实现与 php-command nl2br 相同的效果?

javascript - 如何收集 AngularJS 中已选择的行的数据?

javascript - 为什么 deferred.resolve(object) 之后 deferred.promise 的结果和 myobject 不一样

javascript - 服务 worker js 中的 Fetch() 无法发送请求 header ?

javascript - 如何在 ng-repeat 中进行 ng-model ?

AngularJS 单元测试 $rootScope.$on

asp.net-mvc - 如何检查 asp.net mvc 中的模型验证错误?

ruby-on-rails - rails : validates_length_of :allow_nil does not allow nil

python - Django 模型中的单元测试外键约束