Angular 表单验证 - 将毫秒转换为有效的日期对象
Angular form validation - transforming milliseconds to valid date object
我目前遇到表单验证和毫秒数方面的问题。我想以毫秒为单位的时间在 angular 中不是有效的日期格式,例如angular.isDate(1418645071000)
返回错误。
但是要更改我的代码中的哪些内容才能使表单验证正常工作?我对服务器没有任何限制——这意味着 "Sat Feb 03 2001 00:00:00 GMT+0100 (CET)" 格式的日期也是可以接受的。
angular.isDate 检查提供的参数是否是日期类型的对象。
您首先需要使用 new Date(milliseconds)
将毫秒转换为日期
我在 Whosebug 上找到了基于此线程的解决方案
我将 modelValue 过滤为我的自定义日期格式。因此 viewValue 的格式为 'dd.Mm.yy'.
ngModelCtrl.$formatters.push(function(modelValue) {
if(modelValue) {
var filtered = $filter('date')(modelValue, 'dd.MM.yy');
return filtered;
}
});
使用以下代码,我立即将毫秒数转换为有效日期
/*
// $parse works out how to get the value.
// This returns a function that returns the result of your ng-model expression.
var modelGetter = $parse(attrs['ngModel']);
console.log(modelGetter(scope));
var timeInMilliseconds = modelGetter(scope);
if(timeInMilliseconds != null) {
// This returns a function that lets us set the value of the ng-model binding expression:
var modelSetter = modelGetter.assign;
// This is how you can use it to set the value 'bar' on the given scope.
modelSetter(scope, new Date(timeInMilliseconds));
console.log(modelGetter(scope));
}
我已经相应地更新了 http://plnkr.co/edit/lZZh5VvCzH6yYh1t8xVM?p=preview。现在没有更多的验证错误了。
我目前遇到表单验证和毫秒数方面的问题。我想以毫秒为单位的时间在 angular 中不是有效的日期格式,例如angular.isDate(1418645071000)
返回错误。
但是要更改我的代码中的哪些内容才能使表单验证正常工作?我对服务器没有任何限制——这意味着 "Sat Feb 03 2001 00:00:00 GMT+0100 (CET)" 格式的日期也是可以接受的。
angular.isDate 检查提供的参数是否是日期类型的对象。
您首先需要使用 new Date(milliseconds)
我在 Whosebug 上找到了基于此线程的解决方案
我将 modelValue 过滤为我的自定义日期格式。因此 viewValue 的格式为 'dd.Mm.yy'.
ngModelCtrl.$formatters.push(function(modelValue) {
if(modelValue) {
var filtered = $filter('date')(modelValue, 'dd.MM.yy');
return filtered;
}
});
使用以下代码,我立即将毫秒数转换为有效日期
/*
// $parse works out how to get the value.
// This returns a function that returns the result of your ng-model expression.
var modelGetter = $parse(attrs['ngModel']);
console.log(modelGetter(scope));
var timeInMilliseconds = modelGetter(scope);
if(timeInMilliseconds != null) {
// This returns a function that lets us set the value of the ng-model binding expression:
var modelSetter = modelGetter.assign;
// This is how you can use it to set the value 'bar' on the given scope.
modelSetter(scope, new Date(timeInMilliseconds));
console.log(modelGetter(scope));
}
我已经相应地更新了 http://plnkr.co/edit/lZZh5VvCzH6yYh1t8xVM?p=preview。现在没有更多的验证错误了。