I am using $http.get in a service in to fetch JSON data. One of my object properties in the returned JSON is a date which is not being parsed by AngularJS. I need to bind this property to a date field and I am currently working around it by manually converting the JSON string to a javascript date after fetching the AJAX data as shown below
app.service('MainService', function(){
var self = this;
self.jsonDate = null;
self.parsedDate = null;
// this function will get JSON data from an API in production
self.getData = function(){
var jsonData = "2014-06-13T16:00:00";
// Angular does not convert my JSON data properties into dates
self.jsonDate = jsonData;
// I can work around this by forcing my dates to be parsed
self.parsedDate = moment(jsonData).toDate();
}
});
Is there a cleaner way of doing this? I built a filter that converts a string to a date
app.filter('stringToDate', function () {
return function (input) {
if (!input)
return null;
var date = moment(input);
return date.isValid() ? date.toDate() : null;
};
});
The filter works great if I use it as shown below
<span ng-bind="service.jsonDate | stringToDate | date:'MM/dd/yy'"></span>
but it does not work if I try to use it with ng-model as shown below
<input type="date" ng-model="service.jsonDate | stringToDate"/>
Can a filter be used with ng-model or do I need to stick with manually converting properties to dates? I have a plunker here that demonstrates my current code