错误:[ngModel:datefmt]预计`2015-05-29T19:06:16.693209Z`为日期 - Angular

Yeh*_*uda 54 javascript django angularjs django-rest-framework

我正在angular申请Djangorest-framework...

该应用程序接收到它与从服务器的JSON信息.其中的关键是created_time......这个字段的值是格式根据iso-8601,例如2015-05-29T19:06:16.693209Z.

在客户端我有一个字段:

<input type="time" ng-model="created_time">
Run Code Online (Sandbox Code Playgroud)

但是当数据到达时我得到了这个错误:

Error: [ngModel:datefmt] Expected `2015-05-29T19:06:16.693209Z` to be a date http://errors.angularjs.org/1.3.13/ngModel/datefmt?p0=2015-05-29T19%3A06%3A16.693209Z
at REGEX_STRING_REGEXP (angular.js:63)
at Array.<anonymous> (angular.js:19807)
at Object.ngModelWatch (angular.js:23289)
at Scope.$get.Scope.$digest (angular.js:14235)
at Scope.$get.Scope.$apply (angular.js:14506)
at done (angular.js:9659)
at completeRequest (angular.js:9849)
at XMLHttpRequest.requestLoaded (angular.js:9790)
Run Code Online (Sandbox Code Playgroud)

我已经尝试了一切:(格式与角度文档中的说明完全相同...

PSL*_*PSL 81

这必须发生角度1.3+.对于日期/时间输入,ng-model的1.3+需要是有效的日期对象,不再允许日期的字符串表示.您需要将字符串转换为日期对象($scope.created_time = new Date(dateString))并将其绑定到ng-model.如果您按照错误链接,它有一个关于错误的清晰描述以及如何解决它.

所有与日期相关的输入都要求模型为Date对象.如果模型是其他内容,则会抛出此错误.在这种情况下,Angular不会设置验证错误,因为这些错误会显示给用户,但错误的状态是由错误的应用程序逻辑引起的,而不是由用户引起的.

  • 效果很好,但我不知道为什么它总是需要休息 1 天,例如:转换后的“02/02/2017”变为“01/02/2017”,我是唯一的吗? (2认同)

Kam*_*our 34

如果从REST服务获取数据,则只需将字段转换为日期即可.

$http.get(url).success(function(data){
     $scope.data = data; // get row data
     $scope.data.mydatefield = new Date($scope.data.mydatefield); // convert filed to date
});
Run Code Online (Sandbox Code Playgroud)


Rod*_*ira 18

创建一个转换模型值的简单指令:

HTML:

<input date-input type="time" ng-model="created_time">
Run Code Online (Sandbox Code Playgroud)

指示:

app.directive('dateInput', function(){
    return {
        restrict : 'A',
        scope : {
            ngModel : '='
        },
        link: function (scope) {
            if (scope.ngModel) scope.ngModel = new Date(scope.ngModel);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)


And*_*kov 9

除了PSL的答案.这是如何将角度1.3+要求覆盖为Date对象.

<input type="date" ng-model="book.date" date-format/>

app.directive('dateFormat', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attr, ngModelCtrl) {
      //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;
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

它可以与AngularFire $ firebaseObject一起使用,并且可以与$ bindTo三向绑定一起使用.无需扩展$ firebaseObject服务.它适用于Ionic/cordova应用.

关于jsfiddle的工作示例

基于这个答案