错误发生在我向用户显示已填充的可编辑表单时(而不是在用户输入数据并提交时)。在如下所示的服务中,数据来自 MySQL over REST/JSON:
HTML:
<input class="form-control" type="date" name="dateInput" id="dateOfBirth"
ng-model="user.dateOfBirth">
Controller :
.controller('EditCtrl', function ($scope, $routeParams, UserDetail, $window) {
$scope.user = UserDetail.find({}, {'id': $routeParams.id});
}
服务:
service.factory('UserDetail', function ($resource) {
return $resource(
'http://localhost:8080/ClearsoftDemoBackend/webresources/clearsoft.demo.users/:id',
{id: '@id'},
{
find: {method: 'GET'},
});
});
错误:
错误:[ngModel:datefmt] 预计 2010-05-13T00:00:00-04:00
是一个日期
最佳答案
AngularJS 1.3 添加到输入 [日期 | datetime-local ] 字段一个新的格式化程序/解析器,用于检查模型是否为日期对象并抛出 datefmt 异常。
if (value && !isDate(value)) {
throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
此问题在以前的版本中不存在,我建议考虑升级以避免大噩梦。
一种解决方法是使用自定义 dateFormat 指令重置默认格式化程序/解析器,并使用 momentjs 将字符串格式化、解析为日期。
define(['directives/directives','momentjs'], function(directives,momentjs) {
directives.directive('dateFormat', function() {
return {
require: 'ngModel',
link: function(scope, element, attr, ngModelCtrl) {
var format=attr.dateFormat;
//Angular 1.3 insert a formater that force to set model to date object, otherwise throw exception.
//Reset default angular formatters/parsers
ngModelCtrl.$formatters.length=0;
ngModelCtrl.$parsers.length=0;
ngModelCtrl.$formatters.push(function(valueFromModel) {
//return how data will be shown in input
if(valueFromModel){
// For momentjs > 2.9 moment global va is not defined use momentjs instead of moment.
return moment(valueFromModel).format(format);
}
else
return null;
});
ngModelCtrl.$parsers.push(function(valueFromInput) {
if(valueFromInput){
//For momentjs > 2.9 moment global va is not defined use momentjs instead of moment.
return moment(valueFromInput,format).toDate();
}
else
return null;
});
}
};
});
});
更新 对于 momentjs > 2.9,考虑到没有定义全局变量的时刻。
2.9 "Deprecation warning: Accessing Moment through the global scope is deprecated, and will be removed in an upcoming release."
对于 AMD 需要使用 momentjs
而不是 moment
。即:
return momentjs(valueFromModel).format(format);
关于javascript - 为什么我在 AngularJS 中的日期输入字段抛出类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26853173/