在AngularJS中处理日期输入时,HTML5提供了<input type="date">
元素,它允许用户通过日期选择器选择日期。默认情况下,这种输入类型会返回YYYY-MM-DD格式的字符串值。
<div ng-app="myApp" ng-controller="myCtrl">
<input type="date" ng-model="selectedDate">
<p>选择的日期是: {{selectedDate}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.selectedDate = new Date().toISOString().split('T')[0];
});
</script>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="date" ng-model="selectedDate">
<p>格式化后的日期: {{selectedDate | date:'yyyy-MM-dd'}}</p>
</div>
如果需要将字符串转换为JavaScript Date对象:
app.controller('myCtrl', function($scope) {
$scope.selectedDate = new Date().toISOString().split('T')[0];
$scope.getDateObject = function() {
return new Date($scope.selectedDate);
};
});
原因:浏览器可能不支持type="date"
,或者模型绑定的是Date对象而非字符串。
解决方案:
<input type="date" ng-model="selectedDate" ng-value="selectedDate">
原因:不同浏览器对日期输入的处理方式可能不同。
解决方案:使用AngularJS的$filter
服务统一格式化:
app.controller('myCtrl', function($scope, $filter) {
$scope.formatDate = function(date) {
return $filter('date')(date, 'yyyy-MM-dd');
};
});
原因:直接使用new Date()
设置默认值可能导致格式不匹配。
解决方案:
$scope.selectedDate = $filter('date')(new Date(), 'yyyy-MM-dd');
<input type="date" ng-model="selectedDate" min="2020-01-01" max="2030-12-31">
app.directive('dateInput', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$formatters.push(function(value) {
return new Date(value).toISOString().split('T')[0];
});
}
};
});
对于不支持HTML5日期输入的旧浏览器,可以使用polyfill如:
结合AngularJS指令实现兼容方案。
没有搜到相关的文章