6

My goal is to have a single model for date and time.

Unfortunately I haven't found a stable date-time-picker component for AngularJS Material, so I'm using two elements sharing same model: standard md-datepicker and regular input type="time"

      <md-input-container>
        <md-datepicker ng-model="ctrl.myDateTime" md-placeholder="Enter date"></md-datepicker>
      </md-input-container>
      <md-input-container>
        <input ng-model="ctrl.myDateTime" type="time">
      </md-input-container>

      <span>Date and time chosen: {{ctrl.myDateTime}}</span>

Firstly, I choose date. Once date is chosen, ctrl.myDateTime gets date value with 00:00:00 time (in browser time zone) that is displayed in span. Then I choose time. When time is set, it's displayed in span correctly as well.

The issue here: each time input type="time" losts focus (like onblur), for some reason time fraction is resetted to 00:00:00, but input keeps displaying the user's value.

And that's where I need help. The only thing that I figured out is if input is not wraped with md-input-container then time is resetted only once, and if I change it again, focus lost doesn't reset time.

How to avoid that?

Code sample to reproduce: https://codepen.io/mih-kopylov/pen/KKMxgBK

Mikhail Kopylov
  • 2,008
  • 5
  • 27
  • 58

1 Answers1

0

By changing the type from time to datetime you avoid this.
If you want to have only the time, you need an additional variable for it.

<md-content ng-controller="AppCtrl as ctrl" layout-padding="" ng-cloak="" class="datepickerdemoBasicUsage" ng-app="MyApp">
  <div layout="column">
    <div flex="">
      <md-input-container>
        <md-datepicker ng-model="ctrl.myDateTime" md-placeholder="Enter date"></md-datepicker>
      </md-input-container>
      <md-input-container>
<!-- when time is changed using input inside md-input-container, time is resetted on blur -->
        <input ng-model="ctrl.myDateTime" type="datetime">
      </md-input-container>
<!-- when time is changed using this input, time is resetted but only once -->
      <input ng-model="ctrl.myDateTime" type="datetime">
    </div>
    <span>Date and time chosen: {{ctrl.myDateTime}}</span>
  </div>
</md-content>

If you choose to separate the date and the time, you can use a function with:

myDate.setTime(myTime.getTime());
François B.
  • 1,096
  • 7
  • 19
  • That's not how it worked several versions of Angular Material ago. I've updated version, and faced this issue. And I don't need to have datetime because I want to leverage material datepicker component for date. So I would like to find the reason why it stops working and figure out if I can fix that before using another component – Mikhail Kopylov Nov 15 '20 at 13:10