我需要以dd/MM/yyyy
格式捕获日期数据,并需要将其作为Date对象发送到API。我使用以下指令:
angular.module('tmyapp').directive('formattedDate', function (dateFilter) {
return {
require: 'ngModel',
scope: {
format: "="
},
link: function (scope, element, attrs, ngModelController) {
ngModelController.$parsers.push(function (data) {
//convert data from view format to model format
return dateFilter(data, scope.format); //converted
});
ngModelController.$formatters.push(function (data) {
//convert data from model format to view format
return dateFilter(data, scope.format); //converted
});
}
}
});
//use <input type="text" formatted-date format="'dd/MM/yyyy'" />
它正在将日期对象显示为dd/MM/yyyy
,但无法将dd/MM/yyyy
格式的数据转换为Date对象。
有人可以帮忙吗?
答案 0 :(得分:1)
你必须在解析器中解析日期字符串,如下所示:
angular.module('tmyapp').directive('formattedDate', function (dateFilter) {
return {
require: 'ngModel',
scope: {
format: "="
},
link: function (scope, element, attrs, ngModelController) {
ngModelController.$parsers.push(function (data) {
//convert data from view format to model format
dateArray = data.split("/");
var date = new Date(dateArray[2] + "-" + dateArray[1] + "-" + dateArray[0])
return date; //converted
});
ngModelController.$formatters.push(function (data) {
//convert data from model format to view format
return dateFilter(data, scope.format); //converted
});
}
}
});