I have an HTML5 date input and I would like its value to be set to the value of the date property in my model by default. I\'m not too fussy about formatting since Chrome se
The problem is that value is ignored when ng-model is present.
Firefox, which doesn't currently support type="date"
, will convert all the values to string. Since you (rightly) want date
to be a real Date
object and not a string, I think the best choice is to create another variable, for instance dateString
, and then link the two variables:
function MainCtrl($scope, dateFilter) {
$scope.date = new Date();
$scope.$watch('date', function (date)
{
$scope.dateString = dateFilter(date, 'yyyy-MM-dd');
});
$scope.$watch('dateString', function (dateString)
{
$scope.date = new Date(dateString);
});
}
Fiddle
The actual structure is for demonstration purposes only. You'd be better off creating your own directive, especially in order to:
yyyy-MM-dd
,dateString
variable (see the documentation on this subject).Please notice that I've used yyyy-MM-dd
, because it's a format directly supported by the JavaScript Date
object. In case you want to use another one, you must make the conversion yourself.
EDIT
Here is a way to make a clean directive:
myModule.directive(
'dateInput',
function(dateFilter) {
return {
require: 'ngModel',
template: '',
replace: true,
link: function(scope, elm, attrs, ngModelCtrl) {
ngModelCtrl.$formatters.unshift(function (modelValue) {
return dateFilter(modelValue, 'yyyy-MM-dd');
});
ngModelCtrl.$parsers.unshift(function(viewValue) {
return new Date(viewValue);
});
},
};
});
Fiddle
That's a basic directive, there's still a lot of room for improvement, for example:
yyyy-MM-dd
,