AngularJS 1.4.3 [ngModel: datefmt] Date expected
I am having problems loading date inputs via AJAX. My PHP server is returning dates from a PDO request as JSON strings like 2014-01-27. I've looked at other forum posts that tell me to convert a string to a date object:
$scope.created_time = new Date(dateString);
However, I cannot get it to work on my end. Here is my code for the conversion:
results.data.jobCreated = new Date(results.data.jobCreated);
I even checked the data to make sure it is the date of the object type:
alert(results.data.jobCreated instanceof Date);
This returns a warning with "true", but the browser console still gives me the following error:
Error: [ngModel:datefmt] Expected `2014-01-27` to be a date
http://errors.angularjs.org/1.4.3/ngModel/datefmt?p0=2014-01-27
at REGEX_STRING_REGEXP (angular.js:68)
at Array.<anonymous> (angular.js:21615)
at Object.ngModelWatch (angular.js:25159)
at Scope.$get.Scope.$digest (angular.js:15675)
at Scope.$get.Scope.$apply (angular.js:15951)
at done (angular.js:10364)
at completeRequest (angular.js:10536)
at XMLHttpRequest.requestLoaded (angular.js:10477)
If I show the code directly in the DOM with double curly braces, the following appears:
{"jobCreated":"2014-01-28T00:00:00.000Z"}
This means converting the Date object is working, but I'm not sure why Angular still doesn't accept my Date object.
Thank you for your suggestions.
I should also note that I have a directive that sets the ng-model format to "YYYY-MM-DD" so that I can also validate the date form on the PHP server:
.directive("myModelFilter", ["$filter", function($filter){
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel',
link: function(scope, element, attrs, ngModelController)
{
ngModelController.$parsers.push(function(data) {
//convert data from view format to model format
// Grab the parameters
var params = scope.$eval(attrs.myModelFilter) ;
// Filter with the parameters passed
return $filter(params.filter)(data, params.expr, params.comp);
});
ngModelController.$formatters.push(function(data) {
//convert data from model format to view format
// Grab the parameters
var params = scope.$eval(attrs.myModelFilter) ;
// Filter with the parameters passed
return $filter(params.filter)(data, params.expr, params.comp);
});
}
};
}])
This is the HTML for the input:
<input name="jobCreated" ng-model="formData.jobCreated" required="required" type="date" placeholder="yyyy-mm-dd" my-model-filter="{filter:'date',expr:'yyyy-MM-dd'}" jquery-date-picker="{dateFormat:'yy-mm-dd'}" jquery-mask="{format:'0000-00-00',placeholder:'yyyy-mm-dd'}">
source to share
No one has answered this question yet
See similar questions:
or similar: