简体   繁体   中英

Using Bootstrap datetimepicker in angularJs directive

We have a complex angularJs directive which uses this datetimepicker https://eonasdan.github.io/bootstrap-datetimepicker/ContributorsGuide/#private-functions . The directive works well for many scenarios. We use it as date picker only, time picker only and datetime picker. In the latter case there is a problem. If we have a value already set (with time, say, 00:00) and we pick the date from the calendar (but not the time), the time resets to the current's time. We want to preserve the time in that scenario. My colleague implemented the following code:

  const shouldSaveTime = val !== this.model && !this.changeTimeWithDate && this.hasInitialValueChanged && this.pickTime && this.model; if (shouldSaveTime) { val = services.Date.setTime(val + "", this.model + "").format(this.FORMAT); } 

However, I found that it caused the time not being able to be adjusted manually as well as using time picker portion of the control. So, I commented this code out and got the correct behavior with times except that now picking date only updates the time portion back to the current time. Is there a way to figure out when date only portion of the control was updated through the picker (not typed manually)?

I believe I solved the problem although I don't like that solution much. I added a new property into dp.change event handler in my directive. I then added the following code:

 let preserveSelectedTime = false; if (this.pickTime && !this.changeTimeWithDate) { if (this.dateChangedByPicker) { if (val && modelValue) { //let newDate = Date.parse(val); //let originalDate = Date.parse(modelValue); let newDate = new Date(new Date(val).toDateString()); let originalDate = new Date(new Date(modelValue).toDateString()); if (newDate.valueOf() !== originalDate.valueOf()) { // New date was selected and may be a time preserveSelectedTime = true; } } } } if (preserveSelectedTime) { val = services.Date.setTime(val, modelValue).format(this.FORMAT); } this.setVariable('model', val); this.dateChangedByPicker = false; // Reset this property 

This seems to work OK in my limited tests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM