Javascript 为什么我在 AngularJS 中的日期输入字段会抛出类型错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26853173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:26:52  来源:igfitidea点击:

Why is my date input field in AngularJS throwing type error?

javascripthtmlangularjs

提问by vt97john

The error occurs when I display the populated, editable form to the user (not when a user enters in data and submits). The data is coming from MySQL over REST/JSON in the service shown below:

当我向用户显示填充的、可编辑的表单时(而不是用户输入数据并提交时),就会发生错误。数据来自 MySQL 通过 REST/JSON 在如下所示的服务中:

HTML:

HTML:

<input class="form-control" type="date" name="dateInput" id="dateOfBirth" 
                   ng-model="user.dateOfBirth">

CCONTROLLER:

控制器:

.controller('EditCtrl', function ($scope, $routeParams, UserDetail, $window) {
        $scope.user = UserDetail.find({}, {'id': $routeParams.id});
}

SERVICE:

服务:

service.factory('UserDetail', function ($resource) {

    return $resource(
        'http://localhost:8080/ClearsoftDemoBackend/webresources/clearsoft.demo.users/:id',
        {id: '@id'},
    {
    find: {method: 'GET'},

    });
});

ERROR:

错误:

Error: [ngModel:datefmt] Expected 2010-05-13T00:00:00-04:00to be a date

错误:[ngModel:datefmt] 应2010-05-13T00:00:00-04:00为日期

采纳答案by Matthew Green

Its because that is not a valid date according to Angular. Check out the doc on input[date]for their note on date validation. For it to be a date it should be in the format of YYYY-MM-DD.

这是因为根据 Angular,这不是一个有效的日期。查看 input[date] 上的文档,了解他们关于日期验证的说明。对于它是一个日期,它应该是 YYYY-MM-DD 的格式。

回答by pdorgambide

AngularJS 1.3 adds to input [date | datetime-local ] fields a new formatter/parser that checks that the model is a Date Object and throw the datefmt exception.

AngularJS 1.3 添加到输入 [日期 | datetime-local ] 字段一个新的格式化程序/解析器,用于检查模型是否为日期对象并抛出 datefmt 异常。

if (value && !isDate(value)) {
    throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);

This issue is not present at previos versions and I suggest get in consideration on upgrade to avoid big nightmares.

这个问题在以前的版本中不存在,我建议在升级时考虑一下以避免大噩梦。

A workaroud is to reset default formatters/parser with a custom dateFormat directive and use momentjs to format,parse strings to Date.

一种解决方法是使用自定义 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;
          });
        }
      };
    });
});

UPDATEWith momentjs > 2.9 take in consideration that the moment global var are not defined.

更新对于 momentjs > 2.9 考虑到 moment 全局 var 未定义。

2.9 "Deprecation warning: Accessing Moment through the global scope is deprecated, and will be removed in an upcoming release."

With AMD need use momentjsinstead of moment. i.e:

使用 AMD 需要使用momentjs而不是moment. IE:

return momentjs(valueFromModel).format(format);

回答by Same

In your api

在你的 api

$date = date("Y-m-d");
$new_date = date("c",strtotime($date));
echo json_encode(array("date"=>$new_date));

In your controller

在您的控制器中

/* var date 
* this is value from your api
*/
$scope.date = new Date(date);

回答by Akash Saxena

For date value in an array one can use this as:

对于数组中的日期值,可以将其用作:

    var dates = [
      { id: "1" , date: "2015-04-20T11:24:20.882Z"},
      { id: "2" , date: "2015-05-20T11:24:20.882Z"},
      { id: "3" , date: "2015-06-20T11:24:20.882Z"},
    ];

      function dateStringToObject (data) {
        for(var i=0; i < data.length; i++ ){
          data[i].date = new Date(data[i].date);
          }

        return data;
      }

   dateStringToObject(dates);

回答by Pranay Dutta

Basically its not about the format, it want a valid new Date() object in ISO format ,so whatever you get response ,just do a new Date and angular will be happy , i got this when i parsed the exception message caused by angular

基本上它不是关于格式,它想要一个 ISO 格式的有效 new Date() 对象,所以无论你得到什么响应,只要做一个新的 Date 和 angular 就会很高兴,当我解析由 angular 引起的异常消息时,我得到了这个

https://docs.angularjs.org/error/ngModel/datefmt?p0=2015-11-24

https://docs.angularjs.org/error/ngModel/datefmt?p0=2015-11-24