3

入力がぼやけている場合、または入力が押された場合にのみモデルを更新する必要があり、エラー/成功メッセージは入力中ではなくその後にのみ表示されるという要件があります。以前はAngularJS 1.2 rc2を使用していて、次のコードを持っていました:

Javascript:

angular.module('app', []).directive('ngModelOnblur', function () {
  return {
      restrict: 'A',
      require: 'ngModel',
      link: function (scope, element, attrs, ngModelCtrl) {
          if (attrs.type === 'radio' || attrs.type === 'checkbox') { return; }
          var update = function () {
              scope.$apply(function () {
                  ngModelCtrl.$setViewValue(element.val().trim());
                  ngModelCtrl.$render();
              });
          };
          element.off('input').off('keydown').off('change').on('focus', function () {
              scope.$apply(function () {
                  ngModelCtrl.$setPristine();
              });
          }).on('blur', update).on('keydown', function (e) {
              if (e.keyCode === 13) {
                  update();
              }
          });
      }
  };
})
.controller('Ctrl', ['$scope', function ($scope) {
  $scope.getClass = function (input) {
    if (input.$pristine) { return ''; }
    return input.$invalid ? 'has-error' : 'has-success';
  };
}]);

HTML:

<div ng-controller="Ctrl">
  <form name="form" novalidate>
    <div ng-class="getClass(form.firstname)">
      <input type="text" name="firstname" ng-model="firstname" ng-model-onblur ng-pattern="/^\d{4}$/" />
      <div class="error">error</div>
      <div class="success">success</div>
      $pristine: {{form.firstname.$pristine}}
    </div>
  </form>
</div>

CSS:

  .error, .success {
    display: none; 
  }
  .has-error .error, .has-success .success {
    display: block; 
  }

しかし、RC3 にアップグレードしてから、問題が発生し始めました。入力、変更、およびキーダウンのイベント ハンドラーを削除しましたが、入力時に $pristine が false に設定されているため、メッセージが表示されます。

terminal: trueディレクティブに, を設定しようとpriority: -1しましたが、それでも機能しません。私は何を間違っていますか?

これがプランカーです: http://plnkr.co/edit/8FliNc?p=preview

前もって感謝します

4

2 に答える 2