svichkar
svichkar

Reputation: 1856

How to work with date type input to match both JSON format and date format in AngularJS

I have RESTfull service that produces and consumes JSON object

{
firstName: "Alex",
lastName: "Ross",
studentGroup: {
groupId: 1,
groupName: "java 15-1"
},
admissionDate: "2015-03-25",
status: {
statusId: 3,
statusName: "expelled"
},
term: {
termId: 4,
termName: "fourth"
},
id: 1
}

Here is admissionDate field which coresponds to input with type="date" on html page (page services to update object... so it should display current value and commit new one from date picker to RESTfull service):

<input required type="date" ng-model="student.admissionDate">

So, before representation of current value I converted its String value to date:

$scope.student.admissionDate = new Date(student.admissionDate); 

Input produces date like - 'Fri Mar 11 2016 14:36:29 GMT+0200 (FLE Standard Time)'. BUT service doesn't recognize this format, expected is 'yyyy-MM-dd' format. To avoid errors I use angular filter like

student.admissionDate = $filter('date')($scope.student.admissionDate, "yyyy-MM-dd");

Object can be send to server as well (PUT: /student) but in Chrome developer console I can observe error - "[ngModel:datefmt]" because the value format has been changed in <input> tag.

Chrome console with Angular validation error

How can I solve this problem? What changes should be made to suit both Server format ('yyy-MM-dd') and angular validation in <input type="date">

Upvotes: 3

Views: 1768

Answers (1)

user1846747
user1846747

Reputation:

I think the value you are passing to the filter is a string. You need to do new Date('the_date_string') before passing it to the filter.

That might work.

Upvotes: 1

Related Questions