【问题标题】:Angularjs ngModel typing state directiveAngularjs ngModel 键入状态指令
【发布时间】:2014-09-25 17:41:25
【问题描述】:

我正在使用 angularjs 来验证一个简单的表单。当用户停止输入时,我正在显示我的验证消息。这是自定义指令的一部分,我在其中验证输入的文本在我的服务器上的唯一性。

我的代码有效,但我想知道是否有一种方法可以查看用户是否仍在键入并在所有输入指令中重新使用它的逻辑。当 ngNodel 为 $dirty 时验证用户何时完成输入而不是直接验证用户友好性。

例子:

<input type="text" ng-model="myModel" name="myInput" ng-minlength="8" />
<p ng-show="myFrm.myInput.$error.ngMinlength && !myFrm.myInput.$typing">invalid</p>

那么我该如何创建 $typing 部分,或者它是否以某种形状或形式存在?

我创建了一个解决方案来检查用户是否仍在输入this fiddle 但它不可重复使用。

【问题讨论】:

    标签: angularjs validation angularjs-directive


    【解决方案1】:

    您可以创建另一个与ngModel 同名的指令并使用它添加您的自定义行为,而不是创建另一个仅附加 ngModel 状态的指令。注意:您不必担心它会覆盖原始的 ngModel 指令,它只会运行原始指令和您的自定义指令。

    DEMO

    JAVASCRIPT

     .directive('ngModel', function($timeout) {
        return {
          require: 'ngModel',
          link: function(scope, elem, attr, ngModel) {
            var promise;
    
            ngModel.IS_TYPING_INACTIVE = true;
    
            elem.on('keydown', function() {
    
              ngModel.IS_TYPING_INACTIVE = false;
    
              $timeout.cancel(promise);
              promise = $timeout(function() {
                ngModel.IS_TYPING_INACTIVE = true;
              }, 500);
    
              scope.$apply();
    
            });
          }
        }
      });
    

    HTML(示例用法)

          <div class="form-group" ng-class="{
              'has-error': form.email.$invalid && form.$dirty && form.email.IS_TYPING_INACTIVE,
              'has-success': form.email.$valid && form.$dirty && form.email.IS_TYPING_INACTIVE
            }">
            <input type="email" class="form-control" ng-model="email" name="email" ng-minlength="8" placeholder="Email" required>
    
            <div ng-if="form.email.$invalid && form.$dirty && form.email.IS_TYPING_INACTIVE">
              <span class="help-block" ng-show="form.email.$error.required">This field is required</span>
              <span class="help-block" ng-show="form.email.$error.email">This is not a valid email</span>
              <span class="help-block" ng-show="form.email.$error.minlength">This field must at least have 8 characters</span>
            </div>
    
            <div ng-if="form.email.$valid && form.$dirty && form.email.IS_TYPING_INACTIVE">
              <span class="help-block">Email is valid</span>
            </div>
    
          </div>
    

    【讨论】:

      猜你喜欢
      • 2017-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2016-08-07
      相关资源
      最近更新 更多