指令验证器不会捕获空场而是填充场

时间:2015-05-19 17:24:20

标签: angularjs angularjs-directive

我有以下AngularJS代码。按“提交”按钮时,应检查输入字段是否为空。提交按钮广播指令成功捕获的自定义事件。但是当字段为空时它不起作用。当我开始输入时,它达到ctrl。$ parsers.unshift,我的字段变为theForm.name。$ invalid === true。它似乎以相反的方式工作。

define(['angular'], function (angular) {
  "use strict";

  var requiredValidator = angular.module('RequiredValidator', []);
  requiredValidator.directive('validateRequired', function () {
    var KEY_ERROR = "required";

    return {
      scope: {
        validateRequired: '=validateRequired'
      },
      require: 'ngModel',
      link: function (scope, elem, attr, ctrl) {

        function validate(value) {
          var valid = !value || value === '' || value === null;
          ctrl.$setValidity(KEY_ERROR, valid);
          return value;
        }

        scope.$on('validateEvent', function (event, data) {
          if (scope.validateRequired.$submitted) {
            console.log("Reachable block when submitted");
            ctrl.$parsers.unshift(function (value) {
              console.log("Unreachable when input is empty");
              return validate(value);
            });

            ctrl.$formatters.unshift(function (value) {
              return validate(value);
            });
          }
        });

      }
    };
  });
  return requiredValidator;
});

表单字段摘要:

<div>
  <input type="text" name="name"
  data-ng-class="{ error : theForm.name.$invalid}"
  data-ng-model="customer.name"
  data-validate-required="theForm">
  <span data-ng-show="theForm.name.$invalid" class="error">{{getInputErrorMessage(theForm.name.$error)}}</span>
</div>

1 个答案:

答案 0 :(得分:0)

实际上,你的szenario并不需要这么复杂的指令。您也可以像这样处理控制器中的逻辑:

var app = angular.module('form-example', ['ngMessages']);

app.controller('FormCtrl', function($scope) {
  var vm = this;

  vm.submit = function(form) {
    if (form.$invalid) {
      angular.forEach(form.$error.required, function(item) {
        item.$dirty = true;
      });
      form.$submitted = false;
    } else {
      alert('Form submitted!');
    }
  };
});
label,
button {
  display: block;
}
input {
  margin: 5px 0;
}
button {
  margin-top: 10px;
}
form {
  margin: 10px;
}
div[ng-message] {
  margin-bottom: 10px;
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-messages.js"></script>

<form ng-app="form-example" name="myForm" ng-controller="FormCtrl as vm" novalidate="" ng-submit="vm.submit(myForm)">
  <label for="username">Username</label>
  <input id="username" type="text" name="username" ng-model="vm.username" required="" />
  <div ng-messages="myForm.username.$error" ng-if="myForm.username.$dirty" role="alert">
    <div ng-message="required">Username is required</div>
  </div>
  <label for="email">E-Mail</label>
  <input id="email" type="email" name="email" ng-model="vm.email" required="" />
  <div ng-messages="myForm.email.$error" ng-if="myForm.email.$dirty" role="alert">
    <div ng-message="required">E-Mail is required</div>
    <div ng-message="email">Your E-Mail is not valid</div>
  </div>
  <button type="submit">Send</button>
</form>

这需要至少使用AngularJS 1.3.0版,因为我使用了内部FormController的$submitted属性。有关更多信息,请查看FormController上的documentation。我还使用了ngMessages,这也是1.3中引入的。如果您希望在表单中显示有关错误的消息,这非常有用。