Javascript 模型不是 AngularJS 中输入的日期对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26782917/
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:21:57  来源:igfitidea点击:

Model is not a date object on input in AngularJS

javascriptangularjsdate

提问by Prometheus

Using AngularJS I am trying to display a date using an input type=date:

使用 AngularJS 我试图使用输入显示日期type=date

<input ng-model="campaign.date_start" type="date">

However, this gives the following error:

但是,这会产生以下错误:

Error: error:datefmt
Model is not a date object

The date actually comes from a JSON API in the following format:

日期实际上来自以下格式的 JSON API:

date_start": "2014-11-19"

I thought that I could resolve it by using a filter, but this did not work and I get the same error with:

我以为我可以通过使用过滤器来解决它,但这不起作用,我得到了同样的错误:

 <input ng-model="campaign.date_start | date" type="date">

I have also tried converting the string to a date, but again I get the same error:

我也尝试将字符串转换为日期,但再次出现相同的错误:

 $scope.campaign.date_start = Date(campaign.date_start);

What else can I try?

我还能尝试什么?

采纳答案by ryeballar

You have to instantiate campaign.date_startwith Datenot use it as a function.

您必须实例化campaign.date_startDate不是将其用作函数。

It should look something like this (small demo):

它应该看起来像这样(小演示):

$scope.campaign.date_start = new Date(campaign.date_start);

回答by cs1707

You can use this directive;

你可以使用这个指令;

angular.module('app')
.directive("formatDate", function(){
  return {
   require: 'ngModel',
    link: function(scope, elem, attr, modelCtrl) {
      modelCtrl.$formatters.push(function(modelValue){
        return new Date(modelValue);
      })
    }
  }
})

In your html;

在你的 html 中;

<input type="date" ng-model="date" format-date>

$formatters

Array.<Function>

Array of functions to execute, as a pipeline, whenever the model value changes. The functions are called in reverse array order, each passing the value through to the next. The last return value is used as the actual DOM value. Used to format / convert values for display in the control.

$formatters

Array.<Function>

每当模型值更改时,作为管道执行的函数数组。这些函数以相反的数组顺序调用,每个函数将值传递给下一个。最后一个返回值用作实际的 DOM 值。用于格式化/转换值以在控件中显示。

回答by Jakobovski

cs1707's directive is a great, except if the scope value for the date is nullor undefinedthen it will initialize a date with 1/1/1970. This is probably not optimal for most people

cs1707的指令是一个伟大的,但如果该日期范围值null还是undefined那么它将初始化一个日期1/1/1970。这对大多数人来说可能不是最佳选择

Below is a modified version on cs1707's directive that will leave a null/undefinedmodel as is:

以下是cs1707's 指令的修改版本,它将保留null/undefined模型:

angular.module('app').directive("formatDate", function() {
    return {
        require: 'ngModel',
        link: function(scope, elem, attr, modelCtrl) {
            modelCtrl.$formatters.push(function(modelValue) {
                if (modelValue){
                    return new Date(modelValue);
                }
                else {
                    return null;
                }
            });
        }
    };
});

In your html;

在你的 html 中;

<input type="date" ng-model="date" format-date>

Another Option

另外一个选项

If you want this to apply to all inputs of type date, then there is no need to add the format-date attribute to each input element. You can use the following directive. (Be careful with this as it might interact with other custom directives in unexpected ways.)

如果您希望这适用于所有日期类型的输入,则无需为每个输入元素添加 format-date 属性。您可以使用以下指令。(小心这一点,因为它可能会以意想不到的方式与其他自定义指令交互。)

angular.module('app').directive("input", function() {
    return {
        require: 'ngModel',
        link: function(scope, elem, attr, modelCtrl) {
            if (attr['type'] === 'date'){
                modelCtrl.$formatters.push(function(modelValue) {
                    if (modelValue){
                        return new Date(modelValue);
                    }
                    else {
                        return null;
                    }
                });
            }

        }
    };
});

In your html;

在你的 html 中;

<input type="date" ng-model="date">

回答by jafarbtech

Using directive to reset default angular formatters/parsers by ngModelCtrl.$formatters.length = 0; ngModelCtrl.$parsers.length = 0;

使用指令重置默认的角度格式化程序/解析器 ngModelCtrl.$formatters.length = 0; ngModelCtrl.$parsers.length = 0;

It works for input[type="date"]as well as input[type="time"]. Also works well for cordova app

它适用于input[type="date"]input[type="time"]。也适用于cordova应用程序

HTML :

HTML :

<input date-input type="time" ng-model="created_time">

Angular Directive:

角度指令:

app.directive('dateInput', 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;
        }
    };
});

回答by kcho0

Another directive solution here:

这里的另一个指令解决方案:

//inside directives.js
.directive('dateField', function () {
    return {
        restrict: ' E',
        scope: {
            ngBind: '=ngModel',
            ngLabel: '@'
        },
        replace: true,
        require: 'ngModel',
        controller: function ($scope) {
            if ($scope.ngBind != null) {
                var pattern = /Date\(([^)]+)\)/;
                var results = pattern.exec($scope.ngBind);
                var dt = new Date(parseFloat(results[1]));
                $scope.ngBind = dt;
            };
        },
        templateUrl: 'templates/directives/dateField.html'
    }
})
;

Add a directive template like this:

添加一个指令模板,如下所示:

<!-- app.directives templates/directives/dateField -->
<script id="templates/directives/dateField.html" type="text/ng-template">    
    <label class="item item-input item-stacked-label ">
        <span class="input-label">{{ngLabel}}</span>
        <input type="date" placeholder="" ng-model="ngBind" />
    </label>
</script>

And use it

并使用它

<date-field ng-label="This date..." ng-model="datajson.do.date"></date-field>

Good luck!

祝你好运!

回答by Rodolfo Jorge Nemer Nogueira

Another simple way using a directive:

使用指令的另一种简单方法:

HTML:

HTML:

<input date-input type="time" ng-model="created_time">

Directive:

指示:

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

回答by Usman

You can avoid from this error using this piece of code which is actually a date format error while we pass our date to some function or API

您可以使用这段代码避免此错误,这实际上是我们将日期传递给某个函数或 API 时的日期格式错误

            var options = {
                weekday: "long", year: "numeric", month: "short",
                day: "numeric", hour: "2-digit", minute: "2-digit"
            };
            $scope.campaign.date_start = $scope.campaign.date_start.toLocaleTimeString("en-us", options);

where en-us format = Friday?, ?Feb? ?1?, ?2013? ?06?:?00? ?AM hope this will help others to solve issue, i was facing such error and resolved with this.

其中 en-us 格式 = Friday?, ?Feb? ?1?, ?2013? ?06?:?00? ?AM 希望这能帮助其他人解决问题,我遇到了这样的错误并解决了这个问题。