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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With