I am looking to achieve the following:
Within my controller model, I have a date object that I want users to be able to modify. I need to provide them with two input fields - one for modifying the date and the other for modifying the time. Both input fields should interact with 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 have not been able to find any specific guidance on this particular binding requirement. Typically, the ng-model directive manages the value of the input field. However, in this case, I want to override this value with my own formatting. Additionally, any changes made by the user should be parsed and updated back into the date object.
Given the complexities of date manipulation in vanilla JavaScript, I have opted to utilize moment.js for formatting and parsing dates and strings.
My current approach is as follows:
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, I have encountered issues when attempting to change the input value within the browser, resulting in NaN:NaN...
Some questions that I have regarding this implementation include:
- How can I effectively model this functionality?
- Does this approach align with Angular's philosophy, or am I veering off course?
- Is it possible to seamlessly integrate ng-model and my custom date-format directive?
- Are there simpler alternatives for achieving this desired outcome?