When Json object comes from Server, date is always stored as string.
We need to show that date value in Input box to allow Edit/Update of object. But
<Input type="date>
only understands date object (rightly so), henceforth, we need to convert date string to date object, after receiving json from AJAX call. There are couple of threads on SO, trying to achieve same, but I found accepted answers on those thread not working (not even plunker).
Convert AJAX date to Javascript date for use with ng-model
angularjs | date input not showing ng-model value
- I don't want to let go type="date" (don't want to loose dtPicker of mobile browsers).
- I don't want to write a line everywhere on controller, converting a date string value to date. Though it does work, but I will keep it as last resort.
I tried to solve my problem using directive, and created following directive. I am trying to induce date object via ngModel.$formatters. Console.log inside jsonStrToDate prints str as empty string.
It is not working, What is wrong with my directive here?) :-
.html
<input type="date" name="dateOfReading" class="form-control" id ="dateOfReading"
ng-model="bpReport.dateOfReading"
json-string-to-date
min="1970-01-01" max="2099-12-31" required />
.js
window.angular.module('myApp.directives', [])
.directive('jsonStringToDate', function(){
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
console.log('directive linking called');
function jsonStrToDate(str) {
console.log('input str value' + str + ', and typeof is ' + typeof str);
var d= new Date(str);
console.log(d);
return d;
}
ngModel.$formatters.push(jsonStrToDate);
ngModel.$parsers.push(function(value) {
console.log("value from parser method:- "+ value);
return value;
});
}
};
});
Right now I am using AngularJS 1.3.0 RC1 Version 1.2.20 also had same issue.