I have an input defined as
<input class="datepicker" type="text" ng-model="clientForm.birthDate" />
Which is rigged up to be displayed elsewhere on the page:
<tr> <th>Birth Date</th> <td>{{client.birthDate|date:'mediumDate'}}</td> </tr>
When the page loads the birth date is nicely formatted as something like Dec 22, 2009
. However, when I look inside my <input>
it's shown as Tue Dec 22 2009 00:00:00 GMT-0800 (Pacific Standard Time)
which I guess is how JS renders Date
objects as strings.
Firstly, how do I tell Angular to show the date in the <input>
as something like 12/22/2009
? I can't seem to apply |filters
inside the ng-model
attribute.
Secondly, as soon as I edit the date, even keeping it in it's original format, my other text (inside the <td>
) doesn't seem to apply the |date
filter anymore; it suddenly changes formats to match that of the input textbox. How do I get it to apply the |date
filter every time the model changes?
Related questions:
The ng-model directive binds the value of HTML controls (input, select, text-area) to application data. It is a part of the FormsModule. This directive is used by itself or as part of a larger form. It accepts a domain model as an optional Input.
To set and get the input type date in dd-mm-yyyy format we will use <input> type attribute. The <input> type attribute is used to define a date picker or control field. In this attribute, you can set the range from which day-month-year to which day-month-year date can be selected from.
Date Format. Angular datepipe code. Result. M/d/yy, h:mm a.
Use custom validation of forms http://docs.angularjs.org/guide/forms Demo: http://plnkr.co/edit/NzeauIDVHlgeb6qF75hX?p=preview
Directive using formaters and parsers and MomentJS )
angModule.directive('moDateInput', function ($window) { return { require:'^ngModel', restrict:'A', link:function (scope, elm, attrs, ctrl) { var moment = $window.moment; var dateFormat = attrs.moDateInput; attrs.$observe('moDateInput', function (newValue) { if (dateFormat == newValue || !ctrl.$modelValue) return; dateFormat = newValue; ctrl.$modelValue = new Date(ctrl.$setViewValue); }); ctrl.$formatters.unshift(function (modelValue) { if (!dateFormat || !modelValue) return ""; var retVal = moment(modelValue).format(dateFormat); return retVal; }); ctrl.$parsers.unshift(function (viewValue) { var date = moment(viewValue, dateFormat); return (date && date.isValid() && date.year() > 1950 ) ? date.toDate() : ""; }); } }; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With