Angular UI 日期选择器在为空时验证为 false

Angular UI datepicker validated as false when empty

我在 Angular 1.4.9 中使用 JqueryUI datepicker(1.0.0) 指令来显示出生日期。此字段不是必需的,除非已填写,否则不应对其进行验证。

页面加载后,该字段被验证为 true(如预期)。一旦用户选择了一个日期,它就会再次有效。但是如果我们手动擦除该字段,该字段将变得无效。

<input ui-date="dateOptions" name="dateOfBirth" ng-model="dob"/>

ng-model可以前后设置相同的值,但该值仍然无效。

我创建了一个 JSFiddle 来复制这里的问题。 https://jsfiddle.net/nipuna777/ctsmuv80/

an issue in the validator of the plugin, it is fixed in the master branch/dist/date.js

所以你可以使用该文件而不是 cdn 中的文件来修复它

如@nipuna777 所说,它看起来像是日期选择器中的错误。

我们可以用指令修复它。

jsfiddle.

上的实例

var myApp = angular.module('myApp', ['ui.date']);

myApp.directive('uiDateFix', function($timeout) {
  return {
    restrict: "A",
    require: 'ngModel',
    priority: 100,
    scope: {
      ngRequired: "="
    },
    link: function(scope, elem, attr, ngModel) {
      var originalValidate = null;
      $timeout(function() {
        if (!originalValidate)
          originalValidate = ngModel.$validators.uiDateValidator;
        ngModel.$validators.uiDateValidator = function uiDateValidator2(modelValue, viewValue) {
          //Define correct validations
          if (viewValue || scope.ngRequired)
            return originalValidate(modelValue, viewValue);
          else
            return true;
        }
      }, 500);
    }
  }
});
//myApp.factory('myService', function() {});

myApp.controller('MyCtrl', function($scope) {
  $scope.name = 'Superhero';
  $scope.value = 'Superhero';
  $scope.dateOptions = {
    changeYear: true,
    changeMonth: true,
    yearRange: '1900:-0'
  };
  $scope.isReq = true;
  $scope.dob = ""
})
<script src="https://code.jquery.com/jquery-2.2.1.js" charset="utf-8"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-date/1.0.0/date.js" charset="utf-8"></script>
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">


<body ng-app="myApp">
  <div ng-controller="MyCtrl">
    <h1> Datepicker</h1>
    <form name="person">
      <label for="dateOfBirth">Date of Birth: </label>
      <input ui-date="dateOptions" name="dateOfBirth" ng-model="dob" ui-date-fix ng-required="isReq" />
       <label for="isReq">Required </label>
       <input type="checkbox" name="isReq" ng-model="isReq" />
      <p>
        dob value: {{dob}}
      </p>
      <p>
        dob valid: {{person.dateOfBirth.$valid}}
      </p>
      <p>
        dob errors: {{person.dateOfBirth.$error}}
      </p>

      <hr>

      <h2>Recreating the problem</h2>
      <ol>
        <li>With the field empty dob is valid</li>
        <li>When you select a value from datepicker again the dob field is valid</li>
        <li>When dob is manually removed, the field becomes invalid</li>
      </ol>

    </form>
  </div>
</body>