使用 AngularJS / UI Bootstrap 自定义 $validator 和 getterSetter 消失的值

Values disappearing with AngularJS / UI Bootstrap custom $validator and getterSetter

我的目标是创建一个 UI Bootstrap 也有输入掩码的日期选择器。

datepicker 指令仅验证使用弹出窗口选择的日期 window 而不是用户手动输入的日期,因此我查找了 how to add custom validation 的文本输入。

这些我都有working in this Plunk

以下是重要的部分:

<!-- HTML -->
<span>Errors: {{myForm.myDate.$error}}</span>
<input 
    name="myDate"
    type="text" 
    class="form-control" 
    ng-class="{error: myForm.myDate.$invalid && myForm.myDate.$dirty}"
    datepicker-popup="MM/dd/yyyy" 
    ng-model="dt" 
    is-open="opened" 
    min-date="'09/01/2015'" 
    max-date="'11/11/2015'" 
    ng-required="true" 
    show-weeks="false"
    show-button-bar="false" />


// JavaScript
.controller('DatepickerDemoCtrl', function ($scope) {
  $scope.dt = undefined;

  $scope.open = function($event) {
    $scope.opened = !$scope.opened;
  };

  $scope.today = new Date();
})

.config(function($provide) {
  $provide.decorator('datepickerPopupDirective', function($delegate) {
    var directive = $delegate[0];
    var link = directive.link;

    directive.compile = function() {
      return function(scope, iEl, iAttrs, ctrls) {
        link.apply(this, arguments);

        // use custom validator to enforce date range on hand-entered text
        ctrls[0].$validators.inDateRange = function(modelValue, viewValue) {
          console.log(modelValue, viewValue);

          // use the ranges provided in the attributes for the validation
          var enteredDate = new Date(viewValue)
          ,   min = new Date(iAttrs.minDate)
          ,   max = new Date(iAttrs.maxDate);

          return ctrls[0].$isEmpty(modelValue) 
                 || (min <= enteredDate && enteredDate <= max);
        };

        // apply input mask to the text field
        iEl.mask('99/99/9999');
      };
    };

    return $delegate;
  });  
});

现在我想做一些简单的事情,即在我的输入中添加一个 getterSetter,这样我就可以在将值持久化到模型之前对其进行一些处理。

我更改了元素上的 ng-model,添加 ng-model-options 以引用我的 getterSetter,并添加实际的 getterSetter 方法。

<!-- HTML -->
ng-model="getSetDate" 
ng-model-options="{getterSetter: true}"

// JavaScript
$scope.getSetDate = function(val) {
  if(angular.isDefined(val)) {
    $scope.dt = val;
  } else {
    return val;
  }
};

然而,即使是 this simple Plunk with getterSetter,它基本上什么都不做也会引入错误。如果我:

  1. 输入无效的日期,比如 09/10/2011
  2. 将其更正为有效日期(通过键入),比如 09/10/2015
  3. 价值消失

我不明白为什么引入这个简单的 getterSetter 会导致我的价值丢失。我应该以不同的方式实施吗?

看起来日期选择器实际上还不支持包含 getterSetter 选项的 ng-model-options,但他们希望实现。

https://github.com/angular-ui/bootstrap/issues/4837

编辑: 此外,我还创建了一个 plunk 来通过观看更新辅助模型。我不确定它是否正是您要找的东西,但似乎做了与您通过 getterSetter 尝试做的类似的事情。基本上将以下内容添加到您的工作示例中。

  $scope.dt = undefined;
  $scope.newdt = undefined;

  $scope.$watch('dt', function(){
    if ($scope.dt) 
      $scope.newdt = $scope.dt;
  });