Reputation: 1909
I have a problem here. I want to use Angular Material datepicker in my modal form. I simply added it to my form like this
<md-datepicker ng-model="new.warranty" md-placeholder="Enter date"></md-datepicker>
And if I submitting form I got this:
Sun Apr 03 2016 00:00:00 GMT+0300 (EEST)
But I want to convert data in yyyy-MM-dd format before send, so I tried to convert date format in this way
data.warranty = $filter('date')(Date.parse(data.warranty), 'yyyy-MM-dd');
So my form rly send a required yyyy-MM-dd format, but I get an error every time, when I sumbitting form.
`The ng-model for md-datepicker must be a Date instance. Currently the model is a: string`
so, how can I prevent this error, without using moment.js, if it possible, please.
Upvotes: 3
Views: 10584
Reputation: 667
i've solved this issue by overriding md-datepicke ,Here is code
.directive('mdDatepicker', function ($parse) {
return {
require: 'ngModel',
link: function (scope, elem, attr, ngModel) {
$parse(attr.ngModel).assign(scope, new Date(_.get(scope, attr.ngModel)));
}
}
})
Upvotes: 0
Reputation: 5802
When you use $filter('date')
on your data.warranty
, you transform it from a Date
object to a String
, hence the error.
The fastest way to solve this is to have a duplicate of your date value as a string:
<md-datepicker ng-model="new.warrantyDate" md-placeholder="Enter date"></md-datepicker>
Whenever you submit the form, before making a request, transform the date in the format you need, but don't overwrite the existing date:
data.warranty = $filter('date')(Date.parse(data.warrantyDate), 'yyyy-MM-dd');
Thus your warrantyDate
value will remain a Date
object and will continue working. In case you modify the date in your response, do not forget to synchronize the warrantyDate
with the modified date.
Another option you could try is create a directive that will have different $modelValue
and $viewValue
for your data.warranty
variable. For more information on how you can achieve this, consult the documentation on ngModelController
.
The second option requires a deeper understanding of how angular works, so if you're at the very beginning of your angularjs path, you might go well with the first option.
Upvotes: 6