[英]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
,它實際上什么都不做會引入錯誤。 如果我:
09/10/2011
09/10/2015
我無法弄清楚為什么引入這個簡單的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.