Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model is not a date object on input in AngularJS

Using AngularJS I am trying to display a date using an input 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:

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?

like image 394
Prometheus Avatar asked Nov 06 '14 15:11

Prometheus


2 Answers

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;

<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.

like image 151
cs1707 Avatar answered Nov 05 '22 14:11

cs1707


You have to instantiate campaign.date_start with Date not use it as a function.

It should look something like this (small demo):

$scope.campaign.date_start = new Date(campaign.date_start);
like image 25
ryeballar Avatar answered Nov 05 '22 16:11

ryeballar