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

dip*_*rus 5 javascript validation twitter-bootstrap angularjs angular-ui-bootstrap

我的目标是创建一个也有输入掩码的UI Bootstrap datepicker.

datepicker指令仅验证使用弹出窗口选择的日期,而不是用户手动输入的日期,因此我查找了如何为文本输入添加自定义验证.

在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;
  });  
});
Run Code Online (Sandbox Code Playgroud)

现在我想做一些简单的事情,即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;
  }
};
Run Code Online (Sandbox Code Playgroud)

然而,即使这个简单的Plunk with getterSetter,基本上什么都不做会引入错误.如果我:

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

我无法弄清楚为什么引入这个简单getterSetter导致我的价值丢失.我应该以不同的方式实现这一点吗?

Dav*_*ten 1

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

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

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

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

  $scope.$watch('dt', function(){
    if ($scope.dt) 
      $scope.newdt = $scope.dt;
  });
Run Code Online (Sandbox Code Playgroud)