簡體   English   中英

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

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

我的目標是創建一個也有輸入掩碼的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;
  });  
});

現在我想做一些簡單的事情,即在我的輸入中添加一個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;
  }
};

然而,即使是這個簡單的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

編輯:另外,我創建了一個通過觀看更新二級模型的插件 我不確定它是否正是你正在尋找的東西,但似乎做了類似於你試圖通過getterSetter的東西。 基本上以下內容添加到您的工作示例中。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM