AngularJS输入日期法语
我希望在表单中使用输入[date],使用户能够使用现代浏览器的支持,而不必使用javascript日期选择器。 对于那些使用不支持浏览器的用户,I'v set。两者共同工作。 我使用法语格式(dd/mm/YYYY)AngularJS输入日期法语,angularjs,date,date-format,Angularjs,Date,Date Format,我希望在表单中使用输入[date],使用户能够使用现代浏览器的支持,而不必使用javascript日期选择器。 对于那些使用不支持浏览器的用户,I'v set。两者共同工作。 我使用法语格式(dd/mm/YYYY) $scope.myDate=新日期(“2016-02-12”);//作品 $scope.myDate=“12/02/2016”;//不。。。 以空的形式,没问题,接受它。 但对于填充表单,Angular需要一种我不想要的日期格式:YYYY-mm-dd(javascript日期对象
$scope.myDate=新日期(“2016-02-12”);//作品
$scope.myDate=“12/02/2016”;//不。。。
以空的形式,没问题,接受它。
但对于填充表单,Angular需要一种我不想要的日期格式:YYYY-mm-dd(javascript日期对象)
我不明白为什么Angular只支持该格式,而不支持其他类似法语格式的格式。因为我希望输入[日期]显示法语格式,而不是标准格式
许多现代浏览器都提供了对日期的有趣支持,我不明白为什么会这样
或者我错过了什么?为了实现你的目标,需要使用
momentJs
和ngModel
$parsers
和$formatters
。下面是一些代码和JSFIDLE示例:
在控制器中,您准备了一些法语日期格式的字符串值:
$scope.myDate= '12/02/2016';
在视图中,您将该值设置为input[type=date]
元素的ngModel属性:
<input class="form-control" type="date" ng-model="myDate">
.directive('input', function(dateFilter) {
return {
restrict: 'E',
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
if (
'undefined' !== typeof attrs.type && 'date' === attrs.type && ngModel
) {
ngModel.$formatters.push(function(modelValue) {
return moment(modelValue, "DD/MM/YYYY").toDate();
});
ngModel.$parsers.push(function(viewValue) {
return moment(viewValue).format("DD/MM/YYYY");
});
}
}
}
})
$formatters
数组中的新函数将myDate
修改为javascript日期对象(使用矩解析器非常简单)。$parsers数组中的新函数将输入元素的值修改回法语格式的日期字符串
此解决方案在myDate
和input[type=date]
元素之间提供了双向绑定:
看看你可以在这个堆栈线程上找到一个解决方案:myDate
应该是一个Date
对象,所以$scope.myDate=“12/02/2016”
无效。你想用法语格式将准备好的值从angular app绑定到输入[type=Date]?@enverdzhaparov是的,这就是我的意思。嗯,这不是我想要的。我希望输入显示一个法语格式,并提供一个iso日期,如果这是它需要的。
.directive('input', function(dateFilter) {
return {
restrict: 'E',
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
if (
'undefined' !== typeof attrs.type && 'date' === attrs.type && ngModel
) {
ngModel.$formatters.push(function(modelValue) {
return moment(modelValue, "DD/MM/YYYY").toDate();
});
ngModel.$parsers.push(function(viewValue) {
return moment(viewValue).format("DD/MM/YYYY");
});
}
}
}
})