Search code examples
javascriptangularjsdatemomentjsangular-moment

Date format issue in Angular Moment Picker library


I have below code in my HTML and using Angular v 1.6.3 along with angular moment picker from https://github.com/indrimuska/angular-moment-picker. I want to display calendar using format DD-MM-YYYY.

<div moment-picker="member.memberSince"
    format="DD-MM-YYYY"
    max-view="month"
    start-view="month"
    autoclose="true"
    today="true"
    ng-model="member.memberSince"
    start-date="member.memberSince | date : 'dd-MM-yyyy'">
    {{ member.memberSince | date : 'dd-MM-yyyy' || "Select a date" }}
</div>

I have two problems

  1. When I set member.memberSince from JS code on page load, date is displayed fine e.g. 01-04-2017. But when I select the date from calendar, it shows the date in undesired format e.g. Sat Apr 01 2017 00:00:00 GMT+0530.

enter image description here

enter image description here

  1. If I don't set member.memberSince, then I can't see any control on page to select calendar.

enter image description here

How should I solve this problem?

Plunker


Solution

  • There are multiple issues here.

    Let's have a look at docs | angular-moment-picker#options first,

    moment-picker: Two-way bindable property as formatted datetime string.

    ng-model: Two-way bindable property as Moment.js object.

    Now, we should not have both set to same property for obvious reasons. If you have provided ng-model with same property, it seem to give precendence to that and sets the property to Moment.js object.

    Next, when you have {{memberSince | date : 'dd-MM-yyyy' || "Select a date"}} (where memberSince is set to ng-model), which initially had a string/Date object. But when you select a date, it again becomes Moment.js object which doesn't comply to date:'<my-dateformat>' obviously.

    Solution to your problem (if you haven't figured out yet), would be to remove ng-model set to the directive. And you can freely access memberSince from moment-picker="memberSince" since it would be a formatted string in your provided format i.e. DD-MM-YYYY.

    And in HTML, you can use {{ memberSince || "Select a date" }} without needing to use Angular's date filter since memberSince is just a string containing your selected date in provided format.

    working plunker