I want to do the following:
I have a date object in my controller model and I want to let the user modify it. The user should be given two input fields. The first Input field should modify the date, the other the time. Both input field should work on the same date model.
<input ng-model="model.date" date-format="YYYY-MM-DD">
<input ng-model="model.date" date-format="HH:mm:SS">
I didn't find literature about this binding. Normally the ng-model directive takes care of the value of the input field. Now I want to overwrite this value with my own formatting. Also, if the user changes the input, the changes should be parsed and put back into the date object.
As date manipulation in vanilla js is kind of weird, I used moment.js to format and parse the dates and strings.
My current approach looks like this:
app.directive('dateFormat', function() {
return {
restrict: 'A',
link: function(scope, el, at) {
var format = at.dateFormat;
scope.$watch(at.ngModel, function(date) {
var result = moment(date).format(format);
el.val(result);
});
}
};
});
However this will break as soon as I want to change the input value in the browser. I get some NaN:NaN...
My questions are:
- How can I model this?
- Is this approach valid with the angular philosophy or am I doing something weird here?
- Can I use ng-model and my date-format directive together?
- Is there an easier way to do this?
Dateobject but still allow the user to edit it in an edit field with a date mask applied.