我在输入字段上使用 Bootstrap Datepicker(此处找到: http://mgcrea.github.io/angular-strap/#/datepicker )。默认情况下,日期选择器允许输入日期。如果有效,则设置日期。否则,它将日期设置为当前日期。
我编写了一个指令,该指令使用正则表达式仅输入日期字符。:
maskModelCtrl.$parsers.push(function(inputValue) {
var val = maskRenderLogic(inputValue, mask, maxVal);
setAndRender(maskModelCtrl, val);
return maskReturnLogic(val);
});
我编写了一个指令,用模板标准化日期选择器的输入字段:
angular.module('form.validation').directive('dateMask', ['$parse', function($parse) {
return {
restrict: 'E',
scope: {
date: '='
},
template: '<input ng-model="date" regex-mask="[^0-9 /]" max-length="10" bs-datepicker data-date-format="mm/dd/yyyy" placeholder="mm/dd/yyyy" >',
replace: true
};
}]);
问题是,日期选择器会将任何键盘输入或日期选择转换为当前日期。 (参见 plnkr: http://plnkr.co/edit/oCZnq0UOmaxC83Rv7YSs?p=preview )我认为这些指令不应彼此不兼容。
最佳答案
我意识到您可能已经考虑过这一点,但我正在编写一个处理大量日期(输入、修改等)的应用程序,并且我测试了很多不同的日期选择器。
Angular-UI Bootstrap 日期选择器似乎是最具延展性和可用性的。
话虽如此,您的指令应该利用 $formatters 和 $parsers:
标记:
<input date-validator type="text" ng-model="date"/>
指令
app.directive('dateValidator', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
var validate = function(value) {
//.. do validation logic ../
modifiedValue = value / 2;
// set the validity if needed
ctrl.$setValidity('customDate', false);
//return the modified value
return modifiedValue;
}
// formatters fire when the model directly changes
ctrl.$formatters.unshift(function(value) {
return validate(value);
});
// parsers fire when the model changes via input
ctrl.$parser.unshift(function(value) {
return validate(value);
});
}
}
});
关于AngularJs Bootstrap 日期选择器验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20198650/