mpen mpen - 4 months ago 24x
AngularJS Question

How to format a date using ng-model?

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:

<th>Birth Date</th>

When the page loads the birth date is nicely formatted as something like
Dec 22, 2009
. However, when I look inside my
it's shown as
Tue Dec 22 2009 00:00:00 GMT-0800 (Pacific Standard Time)
which I guess is how JS renders
objects as strings.

Firstly, how do I tell Angular to show the date in the
as something like
? I can't seem to apply
inside the

Secondly, as soon as I edit the date, even keeping it in it's original format, my other text (inside the
) doesn't seem to apply the
filter anymore; it suddenly changes formats to match that of the input textbox. How do I get it to apply the
filter every time the model changes?

Related questions:


Use custom validation of forms Demo:

Directive using formaters and parsers and MomentJS )

angModule.directive('moDateInput', function ($window) {
    return {
        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() : "";