2 * Angular Material Design
3 * https://github.com/angular/material
7 (function( window, angular, undefined ){
12 * @name material.components.datepicker
13 * @description Module for the datepicker component.
16 angular.module('material.components.datepicker', [
18 'material.components.icon',
19 'material.components.virtualRepeat'
28 * @module material.components.datepicker
30 * @param {Date} ng-model The component's model. Should be a Date object.
31 * @param {Date=} md-min-date Expression representing the minimum date.
32 * @param {Date=} md-max-date Expression representing the maximum date.
33 * @param {(function(Date): boolean)=} md-date-filter Function expecting a date and returning a boolean whether it can be selected or not.
36 * `<md-calendar>` is a component that renders a calendar that can be used to select a date.
37 * It is a part of the `<md-datepicker` pane, however it can also be used on it's own.
42 * <md-calendar ng-model="birthday"></md-calendar>
45 CalendarCtrl['$inject'] = ["$element", "$scope", "$$mdDateUtil", "$mdUtil", "$mdConstant", "$mdTheming", "$$rAF", "$attrs", "$mdDateLocale"];
46 angular.module('material.components.datepicker')
47 .directive('mdCalendar', calendarDirective);
50 // TODO(jelbourn): Mac Cmd + left / right == Home / End
51 // TODO(jelbourn): Refactor month element creation to use cloneNode (performance).
52 // TODO(jelbourn): Define virtual scrolling constants (compactness) users can override.
53 // TODO(jelbourn): Animated month transition on ng-model change (virtual-repeat)
54 // TODO(jelbourn): Scroll snapping (virtual repeat)
55 // TODO(jelbourn): Remove superfluous row from short months (virtual-repeat)
56 // TODO(jelbourn): Month headers stick to top when scrolling.
57 // TODO(jelbourn): Previous month opacity is lowered when partially scrolled out of view.
58 // TODO(jelbourn): Support md-calendar standalone on a page (as a tabstop w/ aria-live
59 // announcement and key handling).
60 // Read-only calendar (not just date-picker).
62 function calendarDirective() {
64 template: function(tElement, tAttr) {
65 // TODO(crisbeto): This is a workaround that allows the calendar to work, without
66 // a datepicker, until issue #8585 gets resolved. It can safely be removed
67 // afterwards. This ensures that the virtual repeater scrolls to the proper place on load by
68 // deferring the execution until the next digest. It's necessary only if the calendar is used
69 // without a datepicker, otherwise it's already wrapped in an ngIf.
70 var extraAttrs = tAttr.hasOwnProperty('ngIf') ? '' : 'ng-if="calendarCtrl.isInitialized"';
72 '<div ng-switch="calendarCtrl.currentView" ' + extraAttrs + '>' +
73 '<md-calendar-year ng-switch-when="year"></md-calendar-year>' +
74 '<md-calendar-month ng-switch-default></md-calendar-month>' +
80 minDate: '=mdMinDate',
81 maxDate: '=mdMaxDate',
82 dateFilter: '=mdDateFilter',
83 _currentView: '@mdCurrentView'
85 require: ['ngModel', 'mdCalendar'],
86 controller: CalendarCtrl,
87 controllerAs: 'calendarCtrl',
88 bindToController: true,
89 link: function(scope, element, attrs, controllers) {
90 var ngModelCtrl = controllers[0];
91 var mdCalendarCtrl = controllers[1];
92 mdCalendarCtrl.configureNgModel(ngModelCtrl);
98 * Occasionally the hideVerticalScrollbar method might read an element's
99 * width as 0, because it hasn't been laid out yet. This value will be used
100 * as a fallback, in order to prevent scenarios where the element's width
101 * would otherwise have been set to 0. This value is the "usual" width of a
102 * calendar within a floating calendar pane.
104 var FALLBACK_WIDTH = 340;
106 /** Next identifier for calendar instance. */
107 var nextUniqueId = 0;
110 * Controller for the mdCalendar component.
111 * ngInject @constructor
113 function CalendarCtrl($element, $scope, $$mdDateUtil, $mdUtil,
114 $mdConstant, $mdTheming, $$rAF, $attrs, $mdDateLocale) {
116 $mdTheming($element);
118 /** @final {!angular.JQLite} */
119 this.$element = $element;
121 /** @final {!angular.Scope} */
122 this.$scope = $scope;
125 this.dateUtil = $$mdDateUtil;
128 this.$mdUtil = $mdUtil;
131 this.keyCode = $mdConstant.KEY_CODE;
137 this.$mdDateLocale = $mdDateLocale;
140 this.today = this.dateUtil.createDateAtMidnight();
142 /** @type {!angular.NgModelController} */
143 this.ngModelCtrl = null;
145 /** @type {String} Class applied to the selected date cell. */
146 this.SELECTED_DATE_CLASS = 'md-calendar-selected-date';
148 /** @type {String} Class applied to the cell for today. */
149 this.TODAY_CLASS = 'md-calendar-date-today';
151 /** @type {String} Class applied to the focused cell. */
152 this.FOCUSED_DATE_CLASS = 'md-focus';
154 /** @final {number} Unique ID for this calendar instance. */
155 this.id = nextUniqueId++;
158 * The date that is currently focused or showing in the calendar. This will initially be set
159 * to the ng-model value if set, otherwise to today. It will be updated as the user navigates
160 * to other months. The cell corresponding to the displayDate does not necesarily always have
161 * focus in the document (such as for cases when the user is scrolling the calendar).
164 this.displayDate = null;
167 * The selected date. Keep track of this separately from the ng-model value so that we
168 * can know, when the ng-model value changes, what the previous value was before it's updated
169 * in the component's UI.
173 this.selectedDate = null;
176 * The first date that can be rendered by the calendar. The default is taken
177 * from the mdDateLocale provider and is limited by the mdMinDate.
180 this.firstRenderableDate = null;
183 * The last date that can be rendered by the calendar. The default comes
184 * from the mdDateLocale provider and is limited by the maxDate.
187 this.lastRenderableDate = null;
190 * Used to toggle initialize the root element in the next digest.
193 this.isInitialized = false;
196 * Cache for the width of the element without a scrollbar. Used to hide the scrollbar later on
197 * and to avoid extra reflows when switching between views.
203 * Caches the width of the scrollbar in order to be used when hiding it and to avoid extra reflows.
206 this.scrollbarWidth = 0;
208 // Unless the user specifies so, the calendar should not be a tab stop.
209 // This is necessary because ngAria might add a tabindex to anything with an ng-model
210 // (based on whether or not the user has turned that particular feature on/off).
211 if (!$attrs.tabindex) {
212 $element.attr('tabindex', '-1');
215 var boundKeyHandler = angular.bind(this, this.handleKeyEvent);
219 // If use the md-calendar directly in the body without datepicker,
220 // handleKeyEvent will disable other inputs on the page.
221 // So only apply the handleKeyEvent on the body when the md-calendar inside datepicker,
222 // otherwise apply on the calendar element only.
224 var handleKeyElement;
225 if ($element.parent().hasClass('md-datepicker-calendar')) {
226 handleKeyElement = angular.element(document.body);
228 handleKeyElement = $element;
231 // Bind the keydown handler to the body, in order to handle cases where the focused
232 // element gets removed from the DOM and stops propagating click events.
233 handleKeyElement.on('keydown', boundKeyHandler);
235 $scope.$on('$destroy', function() {
236 handleKeyElement.off('keydown', boundKeyHandler);
239 // For Angular 1.4 and older, where there are no lifecycle hooks but bindings are pre-assigned,
240 // manually call the $onInit hook.
241 if (angular.version.major === 1 && angular.version.minor <= 4) {
248 * Angular Lifecycle hook for newer Angular versions.
249 * Bindings are not guaranteed to have been assigned in the controller, but they are in the $onInit hook.
251 CalendarCtrl.prototype.$onInit = function() {
254 * The currently visible calendar view. Note the prefix on the scope value,
255 * which is necessary, because the datepicker seems to reset the real one value if the
256 * calendar is open, but the value on the datepicker's scope is empty.
259 this.currentView = this._currentView || 'month';
261 var dateLocale = this.$mdDateLocale;
263 if (this.minDate && this.minDate > dateLocale.firstRenderableDate) {
264 this.firstRenderableDate = this.minDate;
266 this.firstRenderableDate = dateLocale.firstRenderableDate;
269 if (this.maxDate && this.maxDate < dateLocale.lastRenderableDate) {
270 this.lastRenderableDate = this.maxDate;
272 this.lastRenderableDate = dateLocale.lastRenderableDate;
277 * Sets up the controller's reference to ngModelController.
278 * @param {!angular.NgModelController} ngModelCtrl
280 CalendarCtrl.prototype.configureNgModel = function(ngModelCtrl) {
283 self.ngModelCtrl = ngModelCtrl;
285 self.$mdUtil.nextTick(function() {
286 self.isInitialized = true;
289 ngModelCtrl.$render = function() {
290 var value = this.$viewValue;
292 // Notify the child scopes of any changes.
293 self.$scope.$broadcast('md-calendar-parent-changed', value);
295 // Set up the selectedDate if it hasn't been already.
296 if (!self.selectedDate) {
297 self.selectedDate = value;
300 // Also set up the displayDate.
301 if (!self.displayDate) {
302 self.displayDate = self.selectedDate || self.today;
308 * Sets the ng-model value for the calendar and emits a change event.
311 CalendarCtrl.prototype.setNgModelValue = function(date) {
312 var value = this.dateUtil.createDateAtMidnight(date);
314 this.$scope.$emit('md-calendar-change', value);
315 this.ngModelCtrl.$setViewValue(value);
316 this.ngModelCtrl.$render();
321 * Sets the current view that should be visible in the calendar
322 * @param {string} newView View name to be set.
323 * @param {number|Date} time Date object or a timestamp for the new display date.
325 CalendarCtrl.prototype.setCurrentView = function(newView, time) {
328 self.$mdUtil.nextTick(function() {
329 self.currentView = newView;
332 self.displayDate = angular.isDate(time) ? time : new Date(time);
338 * Focus the cell corresponding to the given date.
339 * @param {Date} date The date to be focused.
341 CalendarCtrl.prototype.focus = function(date) {
342 if (this.dateUtil.isValidDate(date)) {
343 var previousFocus = this.$element[0].querySelector('.md-focus');
345 previousFocus.classList.remove(this.FOCUSED_DATE_CLASS);
348 var cellId = this.getDateId(date, this.currentView);
349 var cell = document.getElementById(cellId);
351 cell.classList.add(this.FOCUSED_DATE_CLASS);
353 this.displayDate = date;
356 var rootElement = this.$element[0].querySelector('[ng-switch]');
365 * Normalizes the key event into an action name. The action will be broadcast
366 * to the child controllers.
367 * @param {KeyboardEvent} event
368 * @returns {String} The action that should be taken, or null if the key
369 * does not match a calendar shortcut.
371 CalendarCtrl.prototype.getActionFromKeyEvent = function(event) {
372 var keyCode = this.keyCode;
374 switch (event.which) {
375 case keyCode.ENTER: return 'select';
377 case keyCode.RIGHT_ARROW: return 'move-right';
378 case keyCode.LEFT_ARROW: return 'move-left';
380 // TODO(crisbeto): Might want to reconsider using metaKey, because it maps
381 // to the "Windows" key on PC, which opens the start menu or resizes the browser.
382 case keyCode.DOWN_ARROW: return event.metaKey ? 'move-page-down' : 'move-row-down';
383 case keyCode.UP_ARROW: return event.metaKey ? 'move-page-up' : 'move-row-up';
385 case keyCode.PAGE_DOWN: return 'move-page-down';
386 case keyCode.PAGE_UP: return 'move-page-up';
388 case keyCode.HOME: return 'start';
389 case keyCode.END: return 'end';
391 default: return null;
396 * Handles a key event in the calendar with the appropriate action. The action will either
397 * be to select the focused date or to navigate to focus a new date.
398 * @param {KeyboardEvent} event
400 CalendarCtrl.prototype.handleKeyEvent = function(event) {
403 this.$scope.$apply(function() {
404 // Capture escape and emit back up so that a wrapping component
405 // (such as a date-picker) can decide to close.
406 if (event.which == self.keyCode.ESCAPE || event.which == self.keyCode.TAB) {
407 self.$scope.$emit('md-calendar-close');
409 if (event.which == self.keyCode.TAB) {
410 event.preventDefault();
416 // Broadcast the action that any child controllers should take.
417 var action = self.getActionFromKeyEvent(event);
419 event.preventDefault();
420 event.stopPropagation();
421 self.$scope.$broadcast('md-calendar-parent-action', action);
427 * Hides the vertical scrollbar on the calendar scroller of a child controller by
428 * setting the width on the calendar scroller and the `overflow: hidden` wrapper
429 * around the scroller, and then setting a padding-right on the scroller equal
430 * to the width of the browser's scrollbar.
432 * This will cause a reflow.
434 * @param {object} childCtrl The child controller whose scrollbar should be hidden.
436 CalendarCtrl.prototype.hideVerticalScrollbar = function(childCtrl) {
438 var element = childCtrl.$element[0];
439 var scrollMask = element.querySelector('.md-calendar-scroll-mask');
441 if (self.width > 0) {
444 self.$$rAF(function() {
445 var scroller = childCtrl.calendarScroller;
447 self.scrollbarWidth = scroller.offsetWidth - scroller.clientWidth;
448 self.width = element.querySelector('table').offsetWidth;
453 function setWidth() {
454 var width = self.width || FALLBACK_WIDTH;
455 var scrollbarWidth = self.scrollbarWidth;
456 var scroller = childCtrl.calendarScroller;
458 scrollMask.style.width = width + 'px';
459 scroller.style.width = (width + scrollbarWidth) + 'px';
460 scroller.style.paddingRight = scrollbarWidth + 'px';
465 * Gets an identifier for a date unique to the calendar instance for internal
466 * purposes. Not to be displayed.
467 * @param {Date} date The date for which the id is being generated
468 * @param {string} namespace Namespace for the id. (month, year etc.)
471 CalendarCtrl.prototype.getDateId = function(date, namespace) {
473 throw new Error('A namespace for the date id has to be specified.');
487 * Util to trigger an extra digest on a parent scope, in order to to ensure that
488 * any child virtual repeaters have updated. This is necessary, because the virtual
489 * repeater doesn't update the $index the first time around since the content isn't
490 * in place yet. The case, in which this is an issue, is when the repeater has less
491 * than a page of content (e.g. a month or year view has a min or max date).
493 CalendarCtrl.prototype.updateVirtualRepeat = function() {
494 var scope = this.$scope;
495 var virtualRepeatResizeListener = scope.$on('$md-resize-enable', function() {
496 if (!scope.$$phase) {
500 virtualRepeatResizeListener();
508 CalendarMonthCtrl['$inject'] = ["$element", "$scope", "$animate", "$q", "$$mdDateUtil", "$mdDateLocale"];
509 angular.module('material.components.datepicker')
510 .directive('mdCalendarMonth', calendarDirective);
513 * Height of one calendar month tbody. This must be made known to the virtual-repeat and is
514 * subsequently used for scrolling to specific months.
516 var TBODY_HEIGHT = 265;
519 * Height of a calendar month with a single row. This is needed to calculate the offset for
520 * rendering an extra month in virtual-repeat that only contains one row.
522 var TBODY_SINGLE_ROW_HEIGHT = 45;
524 /** Private directive that represents a list of months inside the calendar. */
525 function calendarDirective() {
528 '<table aria-hidden="true" class="md-calendar-day-header"><thead></thead></table>' +
529 '<div class="md-calendar-scroll-mask">' +
530 '<md-virtual-repeat-container class="md-calendar-scroll-container" ' +
531 'md-offset-size="' + (TBODY_SINGLE_ROW_HEIGHT - TBODY_HEIGHT) + '">' +
532 '<table role="grid" tabindex="0" class="md-calendar" aria-readonly="true">' +
534 'md-calendar-month-body ' +
536 'md-virtual-repeat="i in monthCtrl.items" ' +
537 'md-month-offset="$index" ' +
538 'class="md-calendar-month" ' +
539 'md-start-index="monthCtrl.getSelectedMonthIndex()" ' +
540 'md-item-size="' + TBODY_HEIGHT + '">' +
542 // The <tr> ensures that the <tbody> will always have the
543 // proper height, even if it's empty. If it's content is
544 // compiled, the <tr> will be overwritten.
545 '<tr aria-hidden="true" style="height:' + TBODY_HEIGHT + 'px;"></tr>' +
548 '</md-virtual-repeat-container>' +
550 require: ['^^mdCalendar', 'mdCalendarMonth'],
551 controller: CalendarMonthCtrl,
552 controllerAs: 'monthCtrl',
553 bindToController: true,
554 link: function(scope, element, attrs, controllers) {
555 var calendarCtrl = controllers[0];
556 var monthCtrl = controllers[1];
557 monthCtrl.initialize(calendarCtrl);
563 * Controller for the calendar month component.
564 * ngInject @constructor
566 function CalendarMonthCtrl($element, $scope, $animate, $q,
567 $$mdDateUtil, $mdDateLocale) {
569 /** @final {!angular.JQLite} */
570 this.$element = $element;
572 /** @final {!angular.Scope} */
573 this.$scope = $scope;
575 /** @final {!angular.$animate} */
576 this.$animate = $animate;
578 /** @final {!angular.$q} */
582 this.dateUtil = $$mdDateUtil;
585 this.dateLocale = $mdDateLocale;
587 /** @final {HTMLElement} */
588 this.calendarScroller = $element[0].querySelector('.md-virtual-repeat-scroller');
590 /** @type {boolean} */
591 this.isInitialized = false;
593 /** @type {boolean} */
594 this.isMonthTransitionInProgress = false;
599 * Handles a click event on a date cell.
600 * Created here so that every cell can use the same function instance.
601 * @this {HTMLTableCellElement} The cell that was clicked.
603 this.cellClickHandler = function() {
604 var timestamp = $$mdDateUtil.getTimestampFromNode(this);
605 self.$scope.$apply(function() {
606 self.calendarCtrl.setNgModelValue(timestamp);
611 * Handles click events on the month headers. Switches
612 * the calendar to the year view.
613 * @this {HTMLTableCellElement} The cell that was clicked.
615 this.headerClickHandler = function() {
616 self.calendarCtrl.setCurrentView('year', $$mdDateUtil.getTimestampFromNode(this));
620 /*** Initialization ***/
623 * Initialize the controller by saving a reference to the calendar and
624 * setting up the object that will be iterated by the virtual repeater.
626 CalendarMonthCtrl.prototype.initialize = function(calendarCtrl) {
628 * Dummy array-like object for virtual-repeat to iterate over. The length is the total
629 * number of months that can be viewed. We add 2 months: one to include the current month
630 * and one for the last dummy month.
632 * This is shorter than ideal because of a (potential) Firefox bug
633 * https://bugzilla.mozilla.org/show_bug.cgi?id=1181658.
637 length: this.dateUtil.getMonthDistance(
638 calendarCtrl.firstRenderableDate,
639 calendarCtrl.lastRenderableDate
643 this.calendarCtrl = calendarCtrl;
644 this.attachScopeListeners();
645 calendarCtrl.updateVirtualRepeat();
647 // Fire the initial render, since we might have missed it the first time it fired.
648 calendarCtrl.ngModelCtrl && calendarCtrl.ngModelCtrl.$render();
652 * Gets the "index" of the currently selected date as it would be in the virtual-repeat.
655 CalendarMonthCtrl.prototype.getSelectedMonthIndex = function() {
656 var calendarCtrl = this.calendarCtrl;
658 return this.dateUtil.getMonthDistance(
659 calendarCtrl.firstRenderableDate,
660 calendarCtrl.displayDate || calendarCtrl.selectedDate || calendarCtrl.today
665 * Change the selected date in the calendar (ngModel value has already been changed).
668 CalendarMonthCtrl.prototype.changeSelectedDate = function(date) {
670 var calendarCtrl = self.calendarCtrl;
671 var previousSelectedDate = calendarCtrl.selectedDate;
672 calendarCtrl.selectedDate = date;
674 this.changeDisplayDate(date).then(function() {
675 var selectedDateClass = calendarCtrl.SELECTED_DATE_CLASS;
676 var namespace = 'month';
678 // Remove the selected class from the previously selected date, if any.
679 if (previousSelectedDate) {
680 var prevDateCell = document.getElementById(calendarCtrl.getDateId(previousSelectedDate, namespace));
682 prevDateCell.classList.remove(selectedDateClass);
683 prevDateCell.setAttribute('aria-selected', 'false');
687 // Apply the select class to the new selected date if it is set.
689 var dateCell = document.getElementById(calendarCtrl.getDateId(date, namespace));
691 dateCell.classList.add(selectedDateClass);
692 dateCell.setAttribute('aria-selected', 'true');
699 * Change the date that is being shown in the calendar. If the given date is in a different
700 * month, the displayed month will be transitioned.
703 CalendarMonthCtrl.prototype.changeDisplayDate = function(date) {
704 // Initialization is deferred until this function is called because we want to reflect
705 // the starting value of ngModel.
706 if (!this.isInitialized) {
707 this.buildWeekHeader();
708 this.calendarCtrl.hideVerticalScrollbar(this);
709 this.isInitialized = true;
710 return this.$q.when();
713 // If trying to show an invalid date or a transition is in progress, do nothing.
714 if (!this.dateUtil.isValidDate(date) || this.isMonthTransitionInProgress) {
715 return this.$q.when();
718 this.isMonthTransitionInProgress = true;
719 var animationPromise = this.animateDateChange(date);
721 this.calendarCtrl.displayDate = date;
724 animationPromise.then(function() {
725 self.isMonthTransitionInProgress = false;
728 return animationPromise;
732 * Animates the transition from the calendar's current month to the given month.
734 * @returns {angular.$q.Promise} The animation promise.
736 CalendarMonthCtrl.prototype.animateDateChange = function(date) {
737 if (this.dateUtil.isValidDate(date)) {
738 var monthDistance = this.dateUtil.getMonthDistance(this.calendarCtrl.firstRenderableDate, date);
739 this.calendarScroller.scrollTop = monthDistance * TBODY_HEIGHT;
742 return this.$q.when();
746 * Builds and appends a day-of-the-week header to the calendar.
747 * This should only need to be called once during initialization.
749 CalendarMonthCtrl.prototype.buildWeekHeader = function() {
750 var firstDayOfWeek = this.dateLocale.firstDayOfWeek;
751 var shortDays = this.dateLocale.shortDays;
753 var row = document.createElement('tr');
754 for (var i = 0; i < 7; i++) {
755 var th = document.createElement('th');
756 th.textContent = shortDays[(i + firstDayOfWeek) % 7];
760 this.$element.find('thead').append(row);
764 * Attaches listeners for the scope events that are broadcast by the calendar.
766 CalendarMonthCtrl.prototype.attachScopeListeners = function() {
769 self.$scope.$on('md-calendar-parent-changed', function(event, value) {
770 self.changeSelectedDate(value);
773 self.$scope.$on('md-calendar-parent-action', angular.bind(this, this.handleKeyEvent));
777 * Handles the month-specific keyboard interactions.
778 * @param {Object} event Scope event object passed by the calendar.
779 * @param {String} action Action, corresponding to the key that was pressed.
781 CalendarMonthCtrl.prototype.handleKeyEvent = function(event, action) {
782 var calendarCtrl = this.calendarCtrl;
783 var displayDate = calendarCtrl.displayDate;
785 if (action === 'select') {
786 calendarCtrl.setNgModelValue(displayDate);
789 var dateUtil = this.dateUtil;
792 case 'move-right': date = dateUtil.incrementDays(displayDate, 1); break;
793 case 'move-left': date = dateUtil.incrementDays(displayDate, -1); break;
795 case 'move-page-down': date = dateUtil.incrementMonths(displayDate, 1); break;
796 case 'move-page-up': date = dateUtil.incrementMonths(displayDate, -1); break;
798 case 'move-row-down': date = dateUtil.incrementDays(displayDate, 7); break;
799 case 'move-row-up': date = dateUtil.incrementDays(displayDate, -7); break;
801 case 'start': date = dateUtil.getFirstDateOfMonth(displayDate); break;
802 case 'end': date = dateUtil.getLastDateOfMonth(displayDate); break;
806 date = this.dateUtil.clampDate(date, calendarCtrl.minDate, calendarCtrl.maxDate);
808 this.changeDisplayDate(date).then(function() {
809 calendarCtrl.focus(date);
819 mdCalendarMonthBodyDirective['$inject'] = ["$compile", "$$mdSvgRegistry"];
820 CalendarMonthBodyCtrl['$inject'] = ["$element", "$$mdDateUtil", "$mdDateLocale"];
821 angular.module('material.components.datepicker')
822 .directive('mdCalendarMonthBody', mdCalendarMonthBodyDirective);
825 * Private directive consumed by md-calendar-month. Having this directive lets the calender use
826 * md-virtual-repeat and also cleanly separates the month DOM construction functions from
827 * the rest of the calendar controller logic.
830 function mdCalendarMonthBodyDirective($compile, $$mdSvgRegistry) {
831 var ARROW_ICON = $compile('<md-icon md-svg-src="' +
832 $$mdSvgRegistry.mdTabsArrow + '"></md-icon>')({})[0];
835 require: ['^^mdCalendar', '^^mdCalendarMonth', 'mdCalendarMonthBody'],
836 scope: { offset: '=mdMonthOffset' },
837 controller: CalendarMonthBodyCtrl,
838 controllerAs: 'mdMonthBodyCtrl',
839 bindToController: true,
840 link: function(scope, element, attrs, controllers) {
841 var calendarCtrl = controllers[0];
842 var monthCtrl = controllers[1];
843 var monthBodyCtrl = controllers[2];
845 monthBodyCtrl.calendarCtrl = calendarCtrl;
846 monthBodyCtrl.monthCtrl = monthCtrl;
847 monthBodyCtrl.arrowIcon = ARROW_ICON.cloneNode(true);
849 // The virtual-repeat re-uses the same DOM elements, so there are only a limited number
850 // of repeated items that are linked, and then those elements have their bindings updated.
851 // Since the months are not generated by bindings, we simply regenerate the entire thing
852 // when the binding (offset) changes.
853 scope.$watch(function() { return monthBodyCtrl.offset; }, function(offset) {
854 if (angular.isNumber(offset)) {
855 monthBodyCtrl.generateContent();
863 * Controller for a single calendar month.
864 * ngInject @constructor
866 function CalendarMonthBodyCtrl($element, $$mdDateUtil, $mdDateLocale) {
867 /** @final {!angular.JQLite} */
868 this.$element = $element;
871 this.dateUtil = $$mdDateUtil;
874 this.dateLocale = $mdDateLocale;
876 /** @type {Object} Reference to the month view. */
877 this.monthCtrl = null;
879 /** @type {Object} Reference to the calendar. */
880 this.calendarCtrl = null;
883 * Number of months from the start of the month "items" that the currently rendered month
884 * occurs. Set via angular data binding.
890 * Date cell to focus after appending the month to the document.
891 * @type {HTMLElement}
893 this.focusAfterAppend = null;
896 /** Generate and append the content for this month to the directive element. */
897 CalendarMonthBodyCtrl.prototype.generateContent = function() {
898 var date = this.dateUtil.incrementMonths(this.calendarCtrl.firstRenderableDate, this.offset);
902 .append(this.buildCalendarForMonth(date));
904 if (this.focusAfterAppend) {
905 this.focusAfterAppend.classList.add(this.calendarCtrl.FOCUSED_DATE_CLASS);
906 this.focusAfterAppend.focus();
907 this.focusAfterAppend = null;
912 * Creates a single cell to contain a date in the calendar with all appropriate
913 * attributes and classes added. If a date is given, the cell content will be set
915 * @param {Date=} opt_date
916 * @returns {HTMLElement}
918 CalendarMonthBodyCtrl.prototype.buildDateCell = function(opt_date) {
919 var monthCtrl = this.monthCtrl;
920 var calendarCtrl = this.calendarCtrl;
922 // TODO(jelbourn): cloneNode is likely a faster way of doing this.
923 var cell = document.createElement('td');
925 cell.classList.add('md-calendar-date');
926 cell.setAttribute('role', 'gridcell');
929 cell.setAttribute('tabindex', '-1');
930 cell.setAttribute('aria-label', this.dateLocale.longDateFormatter(opt_date));
931 cell.id = calendarCtrl.getDateId(opt_date, 'month');
933 // Use `data-timestamp` attribute because IE10 does not support the `dataset` property.
934 cell.setAttribute('data-timestamp', opt_date.getTime());
936 // TODO(jelourn): Doing these comparisons for class addition during generation might be slow.
937 // It may be better to finish the construction and then query the node and add the class.
938 if (this.dateUtil.isSameDay(opt_date, calendarCtrl.today)) {
939 cell.classList.add(calendarCtrl.TODAY_CLASS);
942 if (this.dateUtil.isValidDate(calendarCtrl.selectedDate) &&
943 this.dateUtil.isSameDay(opt_date, calendarCtrl.selectedDate)) {
944 cell.classList.add(calendarCtrl.SELECTED_DATE_CLASS);
945 cell.setAttribute('aria-selected', 'true');
948 var cellText = this.dateLocale.dates[opt_date.getDate()];
950 if (this.isDateEnabled(opt_date)) {
951 // Add a indicator for select, hover, and focus states.
952 var selectionIndicator = document.createElement('span');
953 selectionIndicator.classList.add('md-calendar-date-selection-indicator');
954 selectionIndicator.textContent = cellText;
955 cell.appendChild(selectionIndicator);
956 cell.addEventListener('click', monthCtrl.cellClickHandler);
958 if (calendarCtrl.displayDate && this.dateUtil.isSameDay(opt_date, calendarCtrl.displayDate)) {
959 this.focusAfterAppend = cell;
962 cell.classList.add('md-calendar-date-disabled');
963 cell.textContent = cellText;
971 * Check whether date is in range and enabled
972 * @param {Date=} opt_date
973 * @return {boolean} Whether the date is enabled.
975 CalendarMonthBodyCtrl.prototype.isDateEnabled = function(opt_date) {
976 return this.dateUtil.isDateWithinRange(opt_date,
977 this.calendarCtrl.minDate, this.calendarCtrl.maxDate) &&
978 (!angular.isFunction(this.calendarCtrl.dateFilter)
979 || this.calendarCtrl.dateFilter(opt_date));
983 * Builds a `tr` element for the calendar grid.
984 * @param rowNumber The week number within the month.
985 * @returns {HTMLElement}
987 CalendarMonthBodyCtrl.prototype.buildDateRow = function(rowNumber) {
988 var row = document.createElement('tr');
989 row.setAttribute('role', 'row');
991 // Because of an NVDA bug (with Firefox), the row needs an aria-label in order
992 // to prevent the entire row being read aloud when the user moves between rows.
993 // See http://community.nvda-project.org/ticket/4643.
994 row.setAttribute('aria-label', this.dateLocale.weekNumberFormatter(rowNumber));
1000 * Builds the <tbody> content for the given date's month.
1001 * @param {Date=} opt_dateInMonth
1002 * @returns {DocumentFragment} A document fragment containing the <tr> elements.
1004 CalendarMonthBodyCtrl.prototype.buildCalendarForMonth = function(opt_dateInMonth) {
1005 var date = this.dateUtil.isValidDate(opt_dateInMonth) ? opt_dateInMonth : new Date();
1007 var firstDayOfMonth = this.dateUtil.getFirstDateOfMonth(date);
1008 var firstDayOfTheWeek = this.getLocaleDay_(firstDayOfMonth);
1009 var numberOfDaysInMonth = this.dateUtil.getNumberOfDaysInMonth(date);
1011 // Store rows for the month in a document fragment so that we can append them all at once.
1012 var monthBody = document.createDocumentFragment();
1015 var row = this.buildDateRow(rowNumber);
1016 monthBody.appendChild(row);
1018 // If this is the final month in the list of items, only the first week should render,
1019 // so we should return immediately after the first row is complete and has been
1020 // attached to the body.
1021 var isFinalMonth = this.offset === this.monthCtrl.items.length - 1;
1023 // Add a label for the month. If the month starts on a Sun/Mon/Tues, the month label
1024 // goes on a row above the first of the month. Otherwise, the month label takes up the first
1025 // two cells of the first row.
1026 var blankCellOffset = 0;
1027 var monthLabelCell = document.createElement('td');
1028 var monthLabelCellContent = document.createElement('span');
1030 monthLabelCellContent.textContent = this.dateLocale.monthHeaderFormatter(date);
1031 monthLabelCell.appendChild(monthLabelCellContent);
1032 monthLabelCell.classList.add('md-calendar-month-label');
1033 // If the entire month is after the max date, render the label as a disabled state.
1034 if (this.calendarCtrl.maxDate && firstDayOfMonth > this.calendarCtrl.maxDate) {
1035 monthLabelCell.classList.add('md-calendar-month-label-disabled');
1037 monthLabelCell.addEventListener('click', this.monthCtrl.headerClickHandler);
1038 monthLabelCell.setAttribute('data-timestamp', firstDayOfMonth.getTime());
1039 monthLabelCell.setAttribute('aria-label', this.dateLocale.monthFormatter(date));
1040 monthLabelCell.appendChild(this.arrowIcon.cloneNode(true));
1043 if (firstDayOfTheWeek <= 2) {
1044 monthLabelCell.setAttribute('colspan', '7');
1046 var monthLabelRow = this.buildDateRow();
1047 monthLabelRow.appendChild(monthLabelCell);
1048 monthBody.insertBefore(monthLabelRow, row);
1054 blankCellOffset = 3;
1055 monthLabelCell.setAttribute('colspan', '3');
1056 row.appendChild(monthLabelCell);
1059 // Add a blank cell for each day of the week that occurs before the first of the month.
1060 // For example, if the first day of the month is a Tuesday, add blank cells for Sun and Mon.
1061 // The blankCellOffset is needed in cases where the first N cells are used by the month label.
1062 for (var i = blankCellOffset; i < firstDayOfTheWeek; i++) {
1063 row.appendChild(this.buildDateCell());
1066 // Add a cell for each day of the month, keeping track of the day of the week so that
1067 // we know when to start a new row.
1068 var dayOfWeek = firstDayOfTheWeek;
1069 var iterationDate = firstDayOfMonth;
1070 for (var d = 1; d <= numberOfDaysInMonth; d++) {
1071 // If we've reached the end of the week, start a new row.
1072 if (dayOfWeek === 7) {
1073 // We've finished the first row, so we're done if this is the final month.
1079 row = this.buildDateRow(rowNumber);
1080 monthBody.appendChild(row);
1083 iterationDate.setDate(d);
1084 var cell = this.buildDateCell(iterationDate);
1085 row.appendChild(cell);
1090 // Ensure that the last row of the month has 7 cells.
1091 while (row.childNodes.length < 7) {
1092 row.appendChild(this.buildDateCell());
1095 // Ensure that all months have 6 rows. This is necessary for now because the virtual-repeat
1096 // requires that all items have exactly the same height.
1097 while (monthBody.childNodes.length < 6) {
1098 var whitespaceRow = this.buildDateRow();
1099 for (var j = 0; j < 7; j++) {
1100 whitespaceRow.appendChild(this.buildDateCell());
1102 monthBody.appendChild(whitespaceRow);
1109 * Gets the day-of-the-week index for a date for the current locale.
1111 * @param {Date} date
1112 * @returns {number} The column index of the date in the calendar.
1114 CalendarMonthBodyCtrl.prototype.getLocaleDay_ = function(date) {
1115 return (date.getDay() + (7 - this.dateLocale.firstDayOfWeek)) % 7;
1122 CalendarYearCtrl['$inject'] = ["$element", "$scope", "$animate", "$q", "$$mdDateUtil"];
1123 angular.module('material.components.datepicker')
1124 .directive('mdCalendarYear', calendarDirective);
1127 * Height of one calendar year tbody. This must be made known to the virtual-repeat and is
1128 * subsequently used for scrolling to specific years.
1130 var TBODY_HEIGHT = 88;
1132 /** Private component, representing a list of years in the calendar. */
1133 function calendarDirective() {
1136 '<div class="md-calendar-scroll-mask">' +
1137 '<md-virtual-repeat-container class="md-calendar-scroll-container">' +
1138 '<table role="grid" tabindex="0" class="md-calendar" aria-readonly="true">' +
1140 'md-calendar-year-body ' +
1141 'role="rowgroup" ' +
1142 'md-virtual-repeat="i in yearCtrl.items" ' +
1143 'md-year-offset="$index" class="md-calendar-year" ' +
1144 'md-start-index="yearCtrl.getFocusedYearIndex()" ' +
1145 'md-item-size="' + TBODY_HEIGHT + '">' +
1146 // The <tr> ensures that the <tbody> will have the proper
1147 // height, even though it may be empty.
1148 '<tr aria-hidden="true" style="height:' + TBODY_HEIGHT + 'px;"></tr>' +
1151 '</md-virtual-repeat-container>' +
1153 require: ['^^mdCalendar', 'mdCalendarYear'],
1154 controller: CalendarYearCtrl,
1155 controllerAs: 'yearCtrl',
1156 bindToController: true,
1157 link: function(scope, element, attrs, controllers) {
1158 var calendarCtrl = controllers[0];
1159 var yearCtrl = controllers[1];
1160 yearCtrl.initialize(calendarCtrl);
1166 * Controller for the mdCalendar component.
1167 * ngInject @constructor
1169 function CalendarYearCtrl($element, $scope, $animate, $q, $$mdDateUtil) {
1171 /** @final {!angular.JQLite} */
1172 this.$element = $element;
1174 /** @final {!angular.Scope} */
1175 this.$scope = $scope;
1177 /** @final {!angular.$animate} */
1178 this.$animate = $animate;
1180 /** @final {!angular.$q} */
1184 this.dateUtil = $$mdDateUtil;
1186 /** @final {HTMLElement} */
1187 this.calendarScroller = $element[0].querySelector('.md-virtual-repeat-scroller');
1189 /** @type {boolean} */
1190 this.isInitialized = false;
1192 /** @type {boolean} */
1193 this.isMonthTransitionInProgress = false;
1198 * Handles a click event on a date cell.
1199 * Created here so that every cell can use the same function instance.
1200 * @this {HTMLTableCellElement} The cell that was clicked.
1202 this.cellClickHandler = function() {
1203 self.calendarCtrl.setCurrentView('month', $$mdDateUtil.getTimestampFromNode(this));
1208 * Initialize the controller by saving a reference to the calendar and
1209 * setting up the object that will be iterated by the virtual repeater.
1211 CalendarYearCtrl.prototype.initialize = function(calendarCtrl) {
1213 * Dummy array-like object for virtual-repeat to iterate over. The length is the total
1214 * number of years that can be viewed. We add 1 extra in order to include the current year.
1217 length: this.dateUtil.getYearDistance(
1218 calendarCtrl.firstRenderableDate,
1219 calendarCtrl.lastRenderableDate
1223 this.calendarCtrl = calendarCtrl;
1224 this.attachScopeListeners();
1225 calendarCtrl.updateVirtualRepeat();
1227 // Fire the initial render, since we might have missed it the first time it fired.
1228 calendarCtrl.ngModelCtrl && calendarCtrl.ngModelCtrl.$render();
1232 * Gets the "index" of the currently selected date as it would be in the virtual-repeat.
1235 CalendarYearCtrl.prototype.getFocusedYearIndex = function() {
1236 var calendarCtrl = this.calendarCtrl;
1238 return this.dateUtil.getYearDistance(
1239 calendarCtrl.firstRenderableDate,
1240 calendarCtrl.displayDate || calendarCtrl.selectedDate || calendarCtrl.today
1245 * Change the date that is highlighted in the calendar.
1246 * @param {Date} date
1248 CalendarYearCtrl.prototype.changeDate = function(date) {
1249 // Initialization is deferred until this function is called because we want to reflect
1250 // the starting value of ngModel.
1251 if (!this.isInitialized) {
1252 this.calendarCtrl.hideVerticalScrollbar(this);
1253 this.isInitialized = true;
1254 return this.$q.when();
1255 } else if (this.dateUtil.isValidDate(date) && !this.isMonthTransitionInProgress) {
1257 var animationPromise = this.animateDateChange(date);
1259 self.isMonthTransitionInProgress = true;
1260 self.calendarCtrl.displayDate = date;
1262 return animationPromise.then(function() {
1263 self.isMonthTransitionInProgress = false;
1269 * Animates the transition from the calendar's current month to the given month.
1270 * @param {Date} date
1271 * @returns {angular.$q.Promise} The animation promise.
1273 CalendarYearCtrl.prototype.animateDateChange = function(date) {
1274 if (this.dateUtil.isValidDate(date)) {
1275 var monthDistance = this.dateUtil.getYearDistance(this.calendarCtrl.firstRenderableDate, date);
1276 this.calendarScroller.scrollTop = monthDistance * TBODY_HEIGHT;
1279 return this.$q.when();
1283 * Handles the year-view-specific keyboard interactions.
1284 * @param {Object} event Scope event object passed by the calendar.
1285 * @param {String} action Action, corresponding to the key that was pressed.
1287 CalendarYearCtrl.prototype.handleKeyEvent = function(event, action) {
1288 var calendarCtrl = this.calendarCtrl;
1289 var displayDate = calendarCtrl.displayDate;
1291 if (action === 'select') {
1292 this.changeDate(displayDate).then(function() {
1293 calendarCtrl.setCurrentView('month', displayDate);
1294 calendarCtrl.focus(displayDate);
1298 var dateUtil = this.dateUtil;
1301 case 'move-right': date = dateUtil.incrementMonths(displayDate, 1); break;
1302 case 'move-left': date = dateUtil.incrementMonths(displayDate, -1); break;
1304 case 'move-row-down': date = dateUtil.incrementMonths(displayDate, 6); break;
1305 case 'move-row-up': date = dateUtil.incrementMonths(displayDate, -6); break;
1309 var min = calendarCtrl.minDate ? dateUtil.getFirstDateOfMonth(calendarCtrl.minDate) : null;
1310 var max = calendarCtrl.maxDate ? dateUtil.getFirstDateOfMonth(calendarCtrl.maxDate) : null;
1311 date = dateUtil.getFirstDateOfMonth(this.dateUtil.clampDate(date, min, max));
1313 this.changeDate(date).then(function() {
1314 calendarCtrl.focus(date);
1321 * Attaches listeners for the scope events that are broadcast by the calendar.
1323 CalendarYearCtrl.prototype.attachScopeListeners = function() {
1326 self.$scope.$on('md-calendar-parent-changed', function(event, value) {
1327 self.changeDate(value);
1330 self.$scope.$on('md-calendar-parent-action', angular.bind(self, self.handleKeyEvent));
1337 CalendarYearBodyCtrl['$inject'] = ["$element", "$$mdDateUtil", "$mdDateLocale"];
1338 angular.module('material.components.datepicker')
1339 .directive('mdCalendarYearBody', mdCalendarYearDirective);
1342 * Private component, consumed by the md-calendar-year, which separates the DOM construction logic
1343 * and allows for the year view to use md-virtual-repeat.
1345 function mdCalendarYearDirective() {
1347 require: ['^^mdCalendar', '^^mdCalendarYear', 'mdCalendarYearBody'],
1348 scope: { offset: '=mdYearOffset' },
1349 controller: CalendarYearBodyCtrl,
1350 controllerAs: 'mdYearBodyCtrl',
1351 bindToController: true,
1352 link: function(scope, element, attrs, controllers) {
1353 var calendarCtrl = controllers[0];
1354 var yearCtrl = controllers[1];
1355 var yearBodyCtrl = controllers[2];
1357 yearBodyCtrl.calendarCtrl = calendarCtrl;
1358 yearBodyCtrl.yearCtrl = yearCtrl;
1360 scope.$watch(function() { return yearBodyCtrl.offset; }, function(offset) {
1361 if (angular.isNumber(offset)) {
1362 yearBodyCtrl.generateContent();
1370 * Controller for a single year.
1371 * ngInject @constructor
1373 function CalendarYearBodyCtrl($element, $$mdDateUtil, $mdDateLocale) {
1374 /** @final {!angular.JQLite} */
1375 this.$element = $element;
1378 this.dateUtil = $$mdDateUtil;
1381 this.dateLocale = $mdDateLocale;
1383 /** @type {Object} Reference to the calendar. */
1384 this.calendarCtrl = null;
1386 /** @type {Object} Reference to the year view. */
1387 this.yearCtrl = null;
1390 * Number of months from the start of the month "items" that the currently rendered month
1391 * occurs. Set via angular data binding.
1397 * Date cell to focus after appending the month to the document.
1398 * @type {HTMLElement}
1400 this.focusAfterAppend = null;
1403 /** Generate and append the content for this year to the directive element. */
1404 CalendarYearBodyCtrl.prototype.generateContent = function() {
1405 var date = this.dateUtil.incrementYears(this.calendarCtrl.firstRenderableDate, this.offset);
1409 .append(this.buildCalendarForYear(date));
1411 if (this.focusAfterAppend) {
1412 this.focusAfterAppend.classList.add(this.calendarCtrl.FOCUSED_DATE_CLASS);
1413 this.focusAfterAppend.focus();
1414 this.focusAfterAppend = null;
1419 * Creates a single cell to contain a year in the calendar.
1420 * @param {number} opt_year Four-digit year.
1421 * @param {number} opt_month Zero-indexed month.
1422 * @returns {HTMLElement}
1424 CalendarYearBodyCtrl.prototype.buildMonthCell = function(year, month) {
1425 var calendarCtrl = this.calendarCtrl;
1426 var yearCtrl = this.yearCtrl;
1427 var cell = this.buildBlankCell();
1429 // Represent this month/year as a date.
1430 var firstOfMonth = new Date(year, month, 1);
1431 cell.setAttribute('aria-label', this.dateLocale.monthFormatter(firstOfMonth));
1432 cell.id = calendarCtrl.getDateId(firstOfMonth, 'year');
1434 // Use `data-timestamp` attribute because IE10 does not support the `dataset` property.
1435 cell.setAttribute('data-timestamp', firstOfMonth.getTime());
1437 if (this.dateUtil.isSameMonthAndYear(firstOfMonth, calendarCtrl.today)) {
1438 cell.classList.add(calendarCtrl.TODAY_CLASS);
1441 if (this.dateUtil.isValidDate(calendarCtrl.selectedDate) &&
1442 this.dateUtil.isSameMonthAndYear(firstOfMonth, calendarCtrl.selectedDate)) {
1443 cell.classList.add(calendarCtrl.SELECTED_DATE_CLASS);
1444 cell.setAttribute('aria-selected', 'true');
1447 var cellText = this.dateLocale.shortMonths[month];
1449 if (this.dateUtil.isMonthWithinRange(firstOfMonth,
1450 calendarCtrl.minDate, calendarCtrl.maxDate)) {
1451 var selectionIndicator = document.createElement('span');
1452 selectionIndicator.classList.add('md-calendar-date-selection-indicator');
1453 selectionIndicator.textContent = cellText;
1454 cell.appendChild(selectionIndicator);
1455 cell.addEventListener('click', yearCtrl.cellClickHandler);
1457 if (calendarCtrl.displayDate && this.dateUtil.isSameMonthAndYear(firstOfMonth, calendarCtrl.displayDate)) {
1458 this.focusAfterAppend = cell;
1461 cell.classList.add('md-calendar-date-disabled');
1462 cell.textContent = cellText;
1469 * Builds a blank cell.
1470 * @return {HTMLTableCellElement}
1472 CalendarYearBodyCtrl.prototype.buildBlankCell = function() {
1473 var cell = document.createElement('td');
1475 cell.classList.add('md-calendar-date');
1476 cell.setAttribute('role', 'gridcell');
1478 cell.setAttribute('tabindex', '-1');
1483 * Builds the <tbody> content for the given year.
1484 * @param {Date} date Date for which the content should be built.
1485 * @returns {DocumentFragment} A document fragment containing the months within the year.
1487 CalendarYearBodyCtrl.prototype.buildCalendarForYear = function(date) {
1488 // Store rows for the month in a document fragment so that we can append them all at once.
1489 var year = date.getFullYear();
1490 var yearBody = document.createDocumentFragment();
1493 // First row contains label and Jan-Jun.
1494 var firstRow = document.createElement('tr');
1495 var labelCell = document.createElement('td');
1496 labelCell.className = 'md-calendar-month-label';
1497 labelCell.textContent = year;
1498 firstRow.appendChild(labelCell);
1500 for (i = 0; i < 6; i++) {
1501 firstRow.appendChild(this.buildMonthCell(year, i));
1503 yearBody.appendChild(firstRow);
1505 // Second row contains a blank cell and Jul-Dec.
1506 var secondRow = document.createElement('tr');
1507 secondRow.appendChild(this.buildBlankCell());
1508 for (i = 6; i < 12; i++) {
1509 secondRow.appendChild(this.buildMonthCell(year, i));
1511 yearBody.appendChild(secondRow);
1522 * @name $mdDateLocaleProvider
1523 * @module material.components.datepicker
1526 * The `$mdDateLocaleProvider` is the provider that creates the `$mdDateLocale` service.
1527 * This provider that allows the user to specify messages, formatters, and parsers for date
1528 * internationalization. The `$mdDateLocale` service itself is consumed by Angular Material
1529 * components that deal with dates.
1531 * @property {(Array<string>)=} months Array of month names (in order).
1532 * @property {(Array<string>)=} shortMonths Array of abbreviated month names.
1533 * @property {(Array<string>)=} days Array of the days of the week (in order).
1534 * @property {(Array<string>)=} shortDays Array of abbreviated dayes of the week.
1535 * @property {(Array<string>)=} dates Array of dates of the month. Only necessary for locales
1536 * using a numeral system other than [1, 2, 3...].
1537 * @property {(Array<string>)=} firstDayOfWeek The first day of the week. Sunday = 0, Monday = 1,
1539 * @property {(function(string): Date)=} parseDate Function to parse a date object from a string.
1540 * @property {(function(Date, string): string)=} formatDate Function to format a date object to a
1541 * string. The datepicker directive also provides the time zone, if it was specified.
1542 * @property {(function(Date): string)=} monthHeaderFormatter Function that returns the label for
1543 * a month given a date.
1544 * @property {(function(Date): string)=} monthFormatter Function that returns the full name of a month
1546 * @property {(function(number): string)=} weekNumberFormatter Function that returns a label for
1547 * a week given the week number.
1548 * @property {(string)=} msgCalendar Translation of the label "Calendar" for the current locale.
1549 * @property {(string)=} msgOpenCalendar Translation of the button label "Open calendar" for the
1551 * @property {Date=} firstRenderableDate The date from which the datepicker calendar will begin
1552 * rendering. Note that this will be ignored if a minimum date is set. Defaults to January 1st 1880.
1553 * @property {Date=} lastRenderableDate The last date that will be rendered by the datepicker
1554 * calendar. Note that this will be ignored if a maximum date is set. Defaults to January 1st 2130.
1558 * myAppModule.config(function($mdDateLocaleProvider) {
1560 * // Example of a French localization.
1561 * $mdDateLocaleProvider.months = ['janvier', 'février', 'mars', ...];
1562 * $mdDateLocaleProvider.shortMonths = ['janv', 'févr', 'mars', ...];
1563 * $mdDateLocaleProvider.days = ['dimanche', 'lundi', 'mardi', ...];
1564 * $mdDateLocaleProvider.shortDays = ['Di', 'Lu', 'Ma', ...];
1566 * // Can change week display to start on Monday.
1567 * $mdDateLocaleProvider.firstDayOfWeek = 1;
1570 * $mdDateLocaleProvider.dates = [1, 2, 3, 4, 5, 6, ...];
1572 * // Example uses moment.js to parse and format dates.
1573 * $mdDateLocaleProvider.parseDate = function(dateString) {
1574 * var m = moment(dateString, 'L', true);
1575 * return m.isValid() ? m.toDate() : new Date(NaN);
1578 * $mdDateLocaleProvider.formatDate = function(date) {
1579 * var m = moment(date);
1580 * return m.isValid() ? m.format('L') : '';
1583 * $mdDateLocaleProvider.monthHeaderFormatter = function(date) {
1584 * return myShortMonths[date.getMonth()] + ' ' + date.getFullYear();
1587 * // In addition to date display, date components also need localized messages
1588 * // for aria-labels for screen-reader users.
1590 * $mdDateLocaleProvider.weekNumberFormatter = function(weekNumber) {
1591 * return 'Semaine ' + weekNumber;
1594 * $mdDateLocaleProvider.msgCalendar = 'Calendrier';
1595 * $mdDateLocaleProvider.msgOpenCalendar = 'Ouvrir le calendrier';
1597 * // You can also set when your calendar begins and ends.
1598 * $mdDateLocaleProvider.firstRenderableDate = new Date(1776, 6, 4);
1599 * $mdDateLocaleProvider.lastRenderableDate = new Date(2012, 11, 21);
1604 angular.module('material.components.datepicker').config(["$provide", function($provide) {
1605 // TODO(jelbourn): Assert provided values are correctly formatted. Need assertions.
1608 function DateLocaleProvider() {
1609 /** Array of full month names. E.g., ['January', 'Febuary', ...] */
1612 /** Array of abbreviated month names. E.g., ['Jan', 'Feb', ...] */
1613 this.shortMonths = null;
1615 /** Array of full day of the week names. E.g., ['Monday', 'Tuesday', ...] */
1618 /** Array of abbreviated dat of the week names. E.g., ['M', 'T', ...] */
1619 this.shortDays = null;
1621 /** Array of dates of a month (1 - 31). Characters might be different in some locales. */
1624 /** Index of the first day of the week. 0 = Sunday, 1 = Monday, etc. */
1625 this.firstDayOfWeek = 0;
1628 * Function that converts the date portion of a Date to a string.
1629 * @type {(function(Date): string)}
1631 this.formatDate = null;
1634 * Function that converts a date string to a Date object (the date portion)
1635 * @type {function(string): Date}
1637 this.parseDate = null;
1640 * Function that formats a Date into a month header string.
1641 * @type {function(Date): string}
1643 this.monthHeaderFormatter = null;
1646 * Function that formats a week number into a label for the week.
1647 * @type {function(number): string}
1649 this.weekNumberFormatter = null;
1652 * Function that formats a date into a long aria-label that is read
1653 * when the focused date changes.
1654 * @type {function(Date): string}
1656 this.longDateFormatter = null;
1659 * ARIA label for the calendar "dialog" used in the datepicker.
1662 this.msgCalendar = '';
1665 * ARIA label for the datepicker's "Open calendar" buttons.
1668 this.msgOpenCalendar = '';
1672 * Factory function that returns an instance of the dateLocale service.
1675 * @returns {DateLocale}
1677 DateLocaleProvider.prototype.$get = function($locale, $filter) {
1679 * Default date-to-string formatting function.
1680 * @param {!Date} date
1681 * @param {string=} timezone
1684 function defaultFormatDate(date, timezone) {
1689 // All of the dates created through ng-material *should* be set to midnight.
1690 // If we encounter a date where the localeTime shows at 11pm instead of midnight,
1691 // we have run into an issue with DST where we need to increment the hour by one:
1692 // var d = new Date(1992, 9, 8, 0, 0, 0);
1693 // d.toLocaleString(); // == "10/7/1992, 11:00:00 PM"
1694 var localeTime = date.toLocaleTimeString();
1695 var formatDate = date;
1696 if (date.getHours() === 0 &&
1697 (localeTime.indexOf('11:') !== -1 || localeTime.indexOf('23:') !== -1)) {
1698 formatDate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 1, 0, 0);
1701 return $filter('date')(formatDate, 'M/d/yyyy', timezone);
1705 * Default string-to-date parsing function.
1706 * @param {string} dateString
1709 function defaultParseDate(dateString) {
1710 return new Date(dateString);
1714 * Default function to determine whether a string makes sense to be
1715 * parsed to a Date object.
1717 * This is very permissive and is just a basic sanity check to ensure that
1718 * things like single integers aren't able to be parsed into dates.
1719 * @param {string} dateString
1720 * @returns {boolean}
1722 function defaultIsDateComplete(dateString) {
1723 dateString = dateString.trim();
1725 // Looks for three chunks of content (either numbers or text) separated
1727 var re = /^(([a-zA-Z]{3,}|[0-9]{1,4})([ \.,]+|[\/\-])){2}([a-zA-Z]{3,}|[0-9]{1,4})$/;
1728 return re.test(dateString);
1732 * Default date-to-string formatter to get a month header.
1733 * @param {!Date} date
1736 function defaultMonthHeaderFormatter(date) {
1737 return service.shortMonths[date.getMonth()] + ' ' + date.getFullYear();
1741 * Default formatter for a month.
1742 * @param {!Date} date
1745 function defaultMonthFormatter(date) {
1746 return service.months[date.getMonth()] + ' ' + date.getFullYear();
1750 * Default week number formatter.
1754 function defaultWeekNumberFormatter(number) {
1755 return 'Week ' + number;
1759 * Default formatter for date cell aria-labels.
1760 * @param {!Date} date
1763 function defaultLongDateFormatter(date) {
1764 // Example: 'Thursday June 18 2015'
1766 service.days[date.getDay()],
1767 service.months[date.getMonth()],
1768 service.dates[date.getDate()],
1773 // The default "short" day strings are the first character of each day,
1774 // e.g., "Monday" => "M".
1775 var defaultShortDays = $locale.DATETIME_FORMATS.SHORTDAY.map(function(day) {
1776 return day.substring(0, 1);
1779 // The default dates are simply the numbers 1 through 31.
1780 var defaultDates = Array(32);
1781 for (var i = 1; i <= 31; i++) {
1782 defaultDates[i] = i;
1785 // Default ARIA messages are in English (US).
1786 var defaultMsgCalendar = 'Calendar';
1787 var defaultMsgOpenCalendar = 'Open calendar';
1789 // Default start/end dates that are rendered in the calendar.
1790 var defaultFirstRenderableDate = new Date(1880, 0, 1);
1791 var defaultLastRendereableDate = new Date(defaultFirstRenderableDate.getFullYear() + 250, 0, 1);
1794 months: this.months || $locale.DATETIME_FORMATS.MONTH,
1795 shortMonths: this.shortMonths || $locale.DATETIME_FORMATS.SHORTMONTH,
1796 days: this.days || $locale.DATETIME_FORMATS.DAY,
1797 shortDays: this.shortDays || defaultShortDays,
1798 dates: this.dates || defaultDates,
1799 firstDayOfWeek: this.firstDayOfWeek || 0,
1800 formatDate: this.formatDate || defaultFormatDate,
1801 parseDate: this.parseDate || defaultParseDate,
1802 isDateComplete: this.isDateComplete || defaultIsDateComplete,
1803 monthHeaderFormatter: this.monthHeaderFormatter || defaultMonthHeaderFormatter,
1804 monthFormatter: this.monthFormatter || defaultMonthFormatter,
1805 weekNumberFormatter: this.weekNumberFormatter || defaultWeekNumberFormatter,
1806 longDateFormatter: this.longDateFormatter || defaultLongDateFormatter,
1807 msgCalendar: this.msgCalendar || defaultMsgCalendar,
1808 msgOpenCalendar: this.msgOpenCalendar || defaultMsgOpenCalendar,
1809 firstRenderableDate: this.firstRenderableDate || defaultFirstRenderableDate,
1810 lastRenderableDate: this.lastRenderableDate || defaultLastRendereableDate
1815 DateLocaleProvider.prototype.$get['$inject'] = ["$locale", "$filter"];
1817 $provide.provider('$mdDateLocale', new DateLocaleProvider());
1825 * Utility for performing date calculations to facilitate operation of the calendar and
1828 angular.module('material.components.datepicker').factory('$$mdDateUtil', function() {
1830 getFirstDateOfMonth: getFirstDateOfMonth,
1831 getNumberOfDaysInMonth: getNumberOfDaysInMonth,
1832 getDateInNextMonth: getDateInNextMonth,
1833 getDateInPreviousMonth: getDateInPreviousMonth,
1834 isInNextMonth: isInNextMonth,
1835 isInPreviousMonth: isInPreviousMonth,
1836 getDateMidpoint: getDateMidpoint,
1837 isSameMonthAndYear: isSameMonthAndYear,
1838 getWeekOfMonth: getWeekOfMonth,
1839 incrementDays: incrementDays,
1840 incrementMonths: incrementMonths,
1841 getLastDateOfMonth: getLastDateOfMonth,
1842 isSameDay: isSameDay,
1843 getMonthDistance: getMonthDistance,
1844 isValidDate: isValidDate,
1845 setDateTimeToMidnight: setDateTimeToMidnight,
1846 createDateAtMidnight: createDateAtMidnight,
1847 isDateWithinRange: isDateWithinRange,
1848 incrementYears: incrementYears,
1849 getYearDistance: getYearDistance,
1850 clampDate: clampDate,
1851 getTimestampFromNode: getTimestampFromNode,
1852 isMonthWithinRange: isMonthWithinRange
1856 * Gets the first day of the month for the given date's month.
1857 * @param {Date} date
1860 function getFirstDateOfMonth(date) {
1861 return new Date(date.getFullYear(), date.getMonth(), 1);
1865 * Gets the number of days in the month for the given date's month.
1869 function getNumberOfDaysInMonth(date) {
1870 return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
1874 * Get an arbitrary date in the month after the given date's month.
1878 function getDateInNextMonth(date) {
1879 return new Date(date.getFullYear(), date.getMonth() + 1, 1);
1883 * Get an arbitrary date in the month before the given date's month.
1887 function getDateInPreviousMonth(date) {
1888 return new Date(date.getFullYear(), date.getMonth() - 1, 1);
1892 * Gets whether two dates have the same month and year.
1895 * @returns {boolean}
1897 function isSameMonthAndYear(d1, d2) {
1898 return d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth();
1902 * Gets whether two dates are the same day (not not necesarily the same time).
1905 * @returns {boolean}
1907 function isSameDay(d1, d2) {
1908 return d1.getDate() == d2.getDate() && isSameMonthAndYear(d1, d2);
1912 * Gets whether a date is in the month immediately after some date.
1913 * @param {Date} startDate The date from which to compare.
1914 * @param {Date} endDate The date to check.
1915 * @returns {boolean}
1917 function isInNextMonth(startDate, endDate) {
1918 var nextMonth = getDateInNextMonth(startDate);
1919 return isSameMonthAndYear(nextMonth, endDate);
1923 * Gets whether a date is in the month immediately before some date.
1924 * @param {Date} startDate The date from which to compare.
1925 * @param {Date} endDate The date to check.
1926 * @returns {boolean}
1928 function isInPreviousMonth(startDate, endDate) {
1929 var previousMonth = getDateInPreviousMonth(startDate);
1930 return isSameMonthAndYear(endDate, previousMonth);
1934 * Gets the midpoint between two dates.
1939 function getDateMidpoint(d1, d2) {
1940 return createDateAtMidnight((d1.getTime() + d2.getTime()) / 2);
1944 * Gets the week of the month that a given date occurs in.
1945 * @param {Date} date
1946 * @returns {number} Index of the week of the month (zero-based).
1948 function getWeekOfMonth(date) {
1949 var firstDayOfMonth = getFirstDateOfMonth(date);
1950 return Math.floor((firstDayOfMonth.getDay() + date.getDate() - 1) / 7);
1954 * Gets a new date incremented by the given number of days. Number of days can be negative.
1955 * @param {Date} date
1956 * @param {number} numberOfDays
1959 function incrementDays(date, numberOfDays) {
1960 return new Date(date.getFullYear(), date.getMonth(), date.getDate() + numberOfDays);
1964 * Gets a new date incremented by the given number of months. Number of months can be negative.
1965 * If the date of the given month does not match the target month, the date will be set to the
1966 * last day of the month.
1967 * @param {Date} date
1968 * @param {number} numberOfMonths
1971 function incrementMonths(date, numberOfMonths) {
1972 // If the same date in the target month does not actually exist, the Date object will
1973 // automatically advance *another* month by the number of missing days.
1974 // For example, if you try to go from Jan. 30 to Feb. 30, you'll end up on March 2.
1975 // So, we check if the month overflowed and go to the last day of the target month instead.
1976 var dateInTargetMonth = new Date(date.getFullYear(), date.getMonth() + numberOfMonths, 1);
1977 var numberOfDaysInMonth = getNumberOfDaysInMonth(dateInTargetMonth);
1978 if (numberOfDaysInMonth < date.getDate()) {
1979 dateInTargetMonth.setDate(numberOfDaysInMonth);
1981 dateInTargetMonth.setDate(date.getDate());
1984 return dateInTargetMonth;
1988 * Get the integer distance between two months. This *only* considers the month and year
1989 * portion of the Date instances.
1991 * @param {Date} start
1993 * @returns {number} Number of months between `start` and `end`. If `end` is before `start`
1994 * chronologically, this number will be negative.
1996 function getMonthDistance(start, end) {
1997 return (12 * (end.getFullYear() - start.getFullYear())) + (end.getMonth() - start.getMonth());
2001 * Gets the last day of the month for the given date.
2002 * @param {Date} date
2005 function getLastDateOfMonth(date) {
2006 return new Date(date.getFullYear(), date.getMonth(), getNumberOfDaysInMonth(date));
2010 * Checks whether a date is valid.
2011 * @param {Date} date
2012 * @return {boolean} Whether the date is a valid Date.
2014 function isValidDate(date) {
2015 return date && date.getTime && !isNaN(date.getTime());
2019 * Sets a date's time to midnight.
2020 * @param {Date} date
2022 function setDateTimeToMidnight(date) {
2023 if (isValidDate(date)) {
2024 date.setHours(0, 0, 0, 0);
2029 * Creates a date with the time set to midnight.
2030 * Drop-in replacement for two forms of the Date constructor:
2031 * 1. No argument for Date representing now.
2032 * 2. Single-argument value representing number of seconds since Unix Epoch
2034 * @param {number|Date=} opt_value
2035 * @return {Date} New date with time set to midnight.
2037 function createDateAtMidnight(opt_value) {
2039 if (angular.isUndefined(opt_value)) {
2042 date = new Date(opt_value);
2044 setDateTimeToMidnight(date);
2049 * Checks if a date is within a min and max range, ignoring the time component.
2050 * If minDate or maxDate are not dates, they are ignored.
2051 * @param {Date} date
2052 * @param {Date} minDate
2053 * @param {Date} maxDate
2055 function isDateWithinRange(date, minDate, maxDate) {
2056 var dateAtMidnight = createDateAtMidnight(date);
2057 var minDateAtMidnight = isValidDate(minDate) ? createDateAtMidnight(minDate) : null;
2058 var maxDateAtMidnight = isValidDate(maxDate) ? createDateAtMidnight(maxDate) : null;
2059 return (!minDateAtMidnight || minDateAtMidnight <= dateAtMidnight) &&
2060 (!maxDateAtMidnight || maxDateAtMidnight >= dateAtMidnight);
2064 * Gets a new date incremented by the given number of years. Number of years can be negative.
2065 * See `incrementMonths` for notes on overflow for specific dates.
2066 * @param {Date} date
2067 * @param {number} numberOfYears
2070 function incrementYears(date, numberOfYears) {
2071 return incrementMonths(date, numberOfYears * 12);
2075 * Get the integer distance between two years. This *only* considers the year portion of the
2078 * @param {Date} start
2080 * @returns {number} Number of months between `start` and `end`. If `end` is before `start`
2081 * chronologically, this number will be negative.
2083 function getYearDistance(start, end) {
2084 return end.getFullYear() - start.getFullYear();
2088 * Clamps a date between a minimum and a maximum date.
2089 * @param {Date} date Date to be clamped
2090 * @param {Date=} minDate Minimum date
2091 * @param {Date=} maxDate Maximum date
2094 function clampDate(date, minDate, maxDate) {
2095 var boundDate = date;
2096 if (minDate && date < minDate) {
2097 boundDate = new Date(minDate.getTime());
2099 if (maxDate && date > maxDate) {
2100 boundDate = new Date(maxDate.getTime());
2106 * Extracts and parses the timestamp from a DOM node.
2107 * @param {HTMLElement} node Node from which the timestamp will be extracted.
2108 * @return {number} Time since epoch.
2110 function getTimestampFromNode(node) {
2111 if (node && node.hasAttribute('data-timestamp')) {
2112 return Number(node.getAttribute('data-timestamp'));
2117 * Checks if a month is within a min and max range, ignoring the date and time components.
2118 * If minDate or maxDate are not dates, they are ignored.
2119 * @param {Date} date
2120 * @param {Date} minDate
2121 * @param {Date} maxDate
2123 function isMonthWithinRange(date, minDate, maxDate) {
2124 var month = date.getMonth();
2125 var year = date.getFullYear();
2127 return (!minDate || minDate.getFullYear() < year || minDate.getMonth() <= month) &&
2128 (!maxDate || maxDate.getFullYear() > year || maxDate.getMonth() >= month);
2137 // TODO(jelbourn): Demo that uses moment.js
2138 // TODO(jelbourn): make sure this plays well with validation and ngMessages.
2139 // TODO(jelbourn): calendar pane doesn't open up outside of visible viewport.
2140 // TODO(jelbourn): forward more attributes to the internal input (required, autofocus, etc.)
2141 // TODO(jelbourn): something better for mobile (calendar panel takes up entire screen?)
2142 // TODO(jelbourn): input behavior (masking? auto-complete?)
2145 DatePickerCtrl['$inject'] = ["$scope", "$element", "$attrs", "$window", "$mdConstant", "$mdTheming", "$mdUtil", "$mdDateLocale", "$$mdDateUtil", "$$rAF", "$filter"];
2146 datePickerDirective['$inject'] = ["$$mdSvgRegistry", "$mdUtil", "$mdAria", "inputDirective"];
2147 angular.module('material.components.datepicker')
2148 .directive('mdDatepicker', datePickerDirective);
2152 * @name mdDatepicker
2153 * @module material.components.datepicker
2155 * @param {Date} ng-model The component's model. Expects a JavaScript Date object.
2156 * @param {Object=} ng-model-options Allows tuning of the way in which `ng-model` is being updated. Also allows
2157 * for a timezone to be specified. <a href="https://docs.angularjs.org/api/ng/directive/ngModelOptions#usage">Read more at the ngModelOptions docs.</a>
2158 * @param {expression=} ng-change Expression evaluated when the model value changes.
2159 * @param {expression=} ng-focus Expression evaluated when the input is focused or the calendar is opened.
2160 * @param {expression=} ng-blur Expression evaluated when focus is removed from the input or the calendar is closed.
2161 * @param {boolean=} ng-disabled Whether the datepicker is disabled.
2162 * @param {boolean=} ng-required Whether a value is required for the datepicker.
2163 * @param {Date=} md-min-date Expression representing a min date (inclusive).
2164 * @param {Date=} md-max-date Expression representing a max date (inclusive).
2165 * @param {(function(Date): boolean)=} md-date-filter Function expecting a date and returning a boolean whether it can be selected or not.
2166 * @param {String=} md-placeholder The date input placeholder value.
2167 * @param {String=} md-open-on-focus When present, the calendar will be opened when the input is focused.
2168 * @param {Boolean=} md-is-open Expression that can be used to open the datepicker's calendar on-demand.
2169 * @param {String=} md-current-view Default open view of the calendar pane. Can be either "month" or "year".
2170 * @param {String=} md-hide-icons Determines which datepicker icons should be hidden. Note that this may cause the
2171 * datepicker to not align properly with other components. **Use at your own risk.** Possible values are:
2172 * * `"all"` - Hides all icons.
2173 * * `"calendar"` - Only hides the calendar icon.
2174 * * `"triangle"` - Only hides the triangle icon.
2175 * @param {Object=} md-date-locale Allows for the values from the `$mdDateLocaleProvider` to be
2176 * ovewritten on a per-element basis (e.g. `msgOpenCalendar` can be overwritten with
2177 * `md-date-locale="{ msgOpenCalendar: 'Open a special calendar' }"`).
2180 * `<md-datepicker>` is a component used to select a single date.
2181 * For information on how to configure internationalization for the date picker,
2182 * see `$mdDateLocaleProvider`.
2184 * This component supports [ngMessages](https://docs.angularjs.org/api/ngMessages/directive/ngMessages).
2185 * Supported attributes are:
2186 * * `required`: whether a required date is not set.
2187 * * `mindate`: whether the selected date is before the minimum allowed date.
2188 * * `maxdate`: whether the selected date is after the maximum allowed date.
2189 * * `debounceInterval`: ms to delay input processing (since last debounce reset); default value 500ms
2192 * <hljs lang="html">
2193 * <md-datepicker ng-model="birthday"></md-datepicker>
2198 function datePickerDirective($$mdSvgRegistry, $mdUtil, $mdAria, inputDirective) {
2200 template: function(tElement, tAttrs) {
2201 // Buttons are not in the tab order because users can open the calendar via keyboard
2202 // interaction on the text input, and multiple tab stops for one component (picker)
2203 // may be confusing.
2204 var hiddenIcons = tAttrs.mdHideIcons;
2205 var ariaLabelValue = tAttrs.ariaLabel || tAttrs.mdPlaceholder;
2207 var calendarButton = (hiddenIcons === 'all' || hiddenIcons === 'calendar') ? '' :
2208 '<md-button class="md-datepicker-button md-icon-button" type="button" ' +
2209 'tabindex="-1" aria-hidden="true" ' +
2210 'ng-click="ctrl.openCalendarPane($event)">' +
2211 '<md-icon class="md-datepicker-calendar-icon" aria-label="md-calendar" ' +
2212 'md-svg-src="' + $$mdSvgRegistry.mdCalendar + '"></md-icon>' +
2215 var triangleButton = '';
2217 if (hiddenIcons !== 'all' && hiddenIcons !== 'triangle') {
2218 triangleButton = '' +
2219 '<md-button type="button" md-no-ink ' +
2220 'class="md-datepicker-triangle-button md-icon-button" ' +
2221 'ng-click="ctrl.openCalendarPane($event)" ' +
2222 'aria-label="{{::ctrl.locale.msgOpenCalendar}}">' +
2223 '<div class="md-datepicker-expand-triangle"></div>' +
2226 tElement.addClass(HAS_TRIANGLE_ICON_CLASS);
2229 return calendarButton +
2230 '<div class="md-datepicker-input-container" ng-class="{\'md-datepicker-focused\': ctrl.isFocused}">' +
2232 (ariaLabelValue ? 'aria-label="' + ariaLabelValue + '" ' : '') +
2233 'class="md-datepicker-input" ' +
2234 'aria-haspopup="true" ' +
2235 'aria-expanded="{{ctrl.isCalendarOpen}}" ' +
2236 'ng-focus="ctrl.setFocused(true)" ' +
2237 'ng-blur="ctrl.setFocused(false)"> ' +
2241 // This pane will be detached from here and re-attached to the document body.
2242 '<div class="md-datepicker-calendar-pane md-whiteframe-z1" id="{{::ctrl.calendarPaneId}}">' +
2243 '<div class="md-datepicker-input-mask">' +
2244 '<div class="md-datepicker-input-mask-opaque"></div>' +
2246 '<div class="md-datepicker-calendar">' +
2247 '<md-calendar role="dialog" aria-label="{{::ctrl.locale.msgCalendar}}" ' +
2248 'md-current-view="{{::ctrl.currentView}}"' +
2249 'md-min-date="ctrl.minDate"' +
2250 'md-max-date="ctrl.maxDate"' +
2251 'md-date-filter="ctrl.dateFilter"' +
2252 'ng-model="ctrl.date" ng-if="ctrl.isCalendarOpen">' +
2257 require: ['ngModel', 'mdDatepicker', '?^mdInputContainer', '?^form'],
2259 minDate: '=mdMinDate',
2260 maxDate: '=mdMaxDate',
2261 placeholder: '@mdPlaceholder',
2262 currentView: '@mdCurrentView',
2263 dateFilter: '=mdDateFilter',
2264 isOpen: '=?mdIsOpen',
2265 debounceInterval: '=mdDebounceInterval',
2266 dateLocale: '=mdDateLocale'
2268 controller: DatePickerCtrl,
2269 controllerAs: 'ctrl',
2270 bindToController: true,
2271 link: function(scope, element, attr, controllers) {
2272 var ngModelCtrl = controllers[0];
2273 var mdDatePickerCtrl = controllers[1];
2274 var mdInputContainer = controllers[2];
2275 var parentForm = controllers[3];
2276 var mdNoAsterisk = $mdUtil.parseAttributeBoolean(attr.mdNoAsterisk);
2278 mdDatePickerCtrl.configureNgModel(ngModelCtrl, mdInputContainer, inputDirective);
2280 if (mdInputContainer) {
2281 // We need to move the spacer after the datepicker itself,
2282 // because md-input-container adds it after the
2283 // md-datepicker-input by default. The spacer gets wrapped in a
2284 // div, because it floats and gets aligned next to the datepicker.
2285 // There are easier ways of working around this with CSS (making the
2286 // datepicker 100% wide, change the `display` etc.), however they
2287 // break the alignment with any other form controls.
2288 var spacer = element[0].querySelector('.md-errors-spacer');
2291 element.after(angular.element('<div>').append(spacer));
2294 mdInputContainer.setHasPlaceholder(attr.mdPlaceholder);
2295 mdInputContainer.input = element;
2296 mdInputContainer.element
2297 .addClass(INPUT_CONTAINER_CLASS)
2298 .toggleClass(HAS_CALENDAR_ICON_CLASS, attr.mdHideIcons !== 'calendar' && attr.mdHideIcons !== 'all');
2300 if (!mdInputContainer.label) {
2301 $mdAria.expect(element, 'aria-label', attr.mdPlaceholder);
2302 } else if(!mdNoAsterisk) {
2303 attr.$observe('required', function(value) {
2304 mdInputContainer.label.toggleClass('md-required', !!value);
2308 scope.$watch(mdInputContainer.isErrorGetter || function() {
2309 return ngModelCtrl.$invalid && (ngModelCtrl.$touched || (parentForm && parentForm.$submitted));
2310 }, mdInputContainer.setInvalid);
2311 } else if (parentForm) {
2312 // If invalid, highlights the input when the parent form is submitted.
2313 var parentSubmittedWatcher = scope.$watch(function() {
2314 return parentForm.$submitted;
2315 }, function(isSubmitted) {
2317 mdDatePickerCtrl.updateErrorState();
2318 parentSubmittedWatcher();
2326 /** Additional offset for the input's `size` attribute, which is updated based on its content. */
2327 var EXTRA_INPUT_SIZE = 3;
2329 /** Class applied to the container if the date is invalid. */
2330 var INVALID_CLASS = 'md-datepicker-invalid';
2332 /** Class applied to the datepicker when it's open. */
2333 var OPEN_CLASS = 'md-datepicker-open';
2335 /** Class applied to the md-input-container, if a datepicker is placed inside it */
2336 var INPUT_CONTAINER_CLASS = '_md-datepicker-floating-label';
2338 /** Class to be applied when the calendar icon is enabled. */
2339 var HAS_CALENDAR_ICON_CLASS = '_md-datepicker-has-calendar-icon';
2341 /** Class to be applied when the triangle icon is enabled. */
2342 var HAS_TRIANGLE_ICON_CLASS = '_md-datepicker-has-triangle-icon';
2344 /** Default time in ms to debounce input event by. */
2345 var DEFAULT_DEBOUNCE_INTERVAL = 500;
2348 * Height of the calendar pane used to check if the pane is going outside the boundary of
2349 * the viewport. See calendar.scss for how $md-calendar-height is computed; an extra 20px is
2350 * also added to space the pane away from the exact edge of the screen.
2352 * This is computed statically now, but can be changed to be measured if the circumstances
2353 * of calendar sizing are changed.
2355 var CALENDAR_PANE_HEIGHT = 368;
2358 * Width of the calendar pane used to check if the pane is going outside the boundary of
2359 * the viewport. See calendar.scss for how $md-calendar-width is computed; an extra 20px is
2360 * also added to space the pane away from the exact edge of the screen.
2362 * This is computed statically now, but can be changed to be measured if the circumstances
2363 * of calendar sizing are changed.
2365 var CALENDAR_PANE_WIDTH = 360;
2367 /** Used for checking whether the current user agent is on iOS or Android. */
2368 var IS_MOBILE_REGEX = /ipad|iphone|ipod|android/i;
2371 * Controller for md-datepicker.
2373 * ngInject @constructor
2375 function DatePickerCtrl($scope, $element, $attrs, $window, $mdConstant,
2376 $mdTheming, $mdUtil, $mdDateLocale, $$mdDateUtil, $$rAF, $filter) {
2379 this.$window = $window;
2382 this.dateUtil = $$mdDateUtil;
2385 this.$mdConstant = $mdConstant;
2388 this.$mdUtil = $mdUtil;
2394 this.$mdDateLocale = $mdDateLocale;
2397 * The root document element. This is used for attaching a top-level click handler to
2398 * close the calendar panel when a click outside said panel occurs. We use `documentElement`
2399 * instead of body because, when scrolling is disabled, some browsers consider the body element
2400 * to be completely off the screen and propagate events directly to the html element.
2401 * @type {!angular.JQLite}
2403 this.documentElement = angular.element(document.documentElement);
2405 /** @type {!angular.NgModelController} */
2406 this.ngModelCtrl = null;
2408 /** @type {HTMLInputElement} */
2409 this.inputElement = $element[0].querySelector('input');
2411 /** @final {!angular.JQLite} */
2412 this.ngInputElement = angular.element(this.inputElement);
2414 /** @type {HTMLElement} */
2415 this.inputContainer = $element[0].querySelector('.md-datepicker-input-container');
2417 /** @type {HTMLElement} Floating calendar pane. */
2418 this.calendarPane = $element[0].querySelector('.md-datepicker-calendar-pane');
2420 /** @type {HTMLElement} Calendar icon button. */
2421 this.calendarButton = $element[0].querySelector('.md-datepicker-button');
2424 * Element covering everything but the input in the top of the floating calendar pane.
2425 * @type {!angular.JQLite}
2427 this.inputMask = angular.element($element[0].querySelector('.md-datepicker-input-mask-opaque'));
2429 /** @final {!angular.JQLite} */
2430 this.$element = $element;
2432 /** @final {!angular.Attributes} */
2433 this.$attrs = $attrs;
2435 /** @final {!angular.Scope} */
2436 this.$scope = $scope;
2441 /** @type {boolean} */
2442 this.isFocused = false;
2444 /** @type {boolean} */
2446 this.setDisabled($element[0].disabled || angular.isString($attrs.disabled));
2448 /** @type {boolean} Whether the date-picker's calendar pane is open. */
2449 this.isCalendarOpen = false;
2451 /** @type {boolean} Whether the calendar should open when the input is focused. */
2452 this.openOnFocus = $attrs.hasOwnProperty('mdOpenOnFocus');
2455 this.mdInputContainer = null;
2458 * Element from which the calendar pane was opened. Keep track of this so that we can return
2459 * focus to it when the pane is closed.
2460 * @type {HTMLElement}
2462 this.calendarPaneOpenedFrom = null;
2464 /** @type {String} Unique id for the calendar pane. */
2465 this.calendarPaneId = 'md-date-pane-' + $mdUtil.nextUid();
2467 /** Pre-bound click handler is saved so that the event listener can be removed. */
2468 this.bodyClickHandler = angular.bind(this, this.handleBodyClick);
2471 * Name of the event that will trigger a close. Necessary to sniff the browser, because
2472 * the resize event doesn't make sense on mobile and can have a negative impact since it
2473 * triggers whenever the browser zooms in on a focused input.
2475 this.windowEventName = IS_MOBILE_REGEX.test(
2476 navigator.userAgent || navigator.vendor || window.opera
2477 ) ? 'orientationchange' : 'resize';
2479 /** Pre-bound close handler so that the event listener can be removed. */
2480 this.windowEventHandler = $mdUtil.debounce(angular.bind(this, this.closeCalendarPane), 100);
2482 /** Pre-bound handler for the window blur event. Allows for it to be removed later. */
2483 this.windowBlurHandler = angular.bind(this, this.handleWindowBlur);
2485 /** The built-in Angular date filter. */
2486 this.ngDateFilter = $filter('date');
2488 /** @type {Number} Extra margin for the left side of the floating calendar pane. */
2489 this.leftMargin = 20;
2491 /** @type {Number} Extra margin for the top of the floating calendar. Gets determined on the first open. */
2492 this.topMargin = null;
2494 // Unless the user specifies so, the datepicker should not be a tab stop.
2495 // This is necessary because ngAria might add a tabindex to anything with an ng-model
2496 // (based on whether or not the user has turned that particular feature on/off).
2497 if ($attrs.tabindex) {
2498 this.ngInputElement.attr('tabindex', $attrs.tabindex);
2499 $attrs.$set('tabindex', null);
2501 $attrs.$set('tabindex', '-1');
2504 $attrs.$set('aria-owns', this.calendarPaneId);
2506 $mdTheming($element);
2507 $mdTheming(angular.element(this.calendarPane));
2511 $scope.$on('$destroy', function() {
2512 self.detachCalendarPane();
2515 if ($attrs.mdIsOpen) {
2516 $scope.$watch('ctrl.isOpen', function(shouldBeOpen) {
2518 self.openCalendarPane({
2519 target: self.inputElement
2522 self.closeCalendarPane();
2527 // For Angular 1.4 and older, where there are no lifecycle hooks but bindings are pre-assigned,
2528 // manually call the $onInit hook.
2529 if (angular.version.major === 1 && angular.version.minor <= 4) {
2536 * Angular Lifecycle hook for newer Angular versions.
2537 * Bindings are not guaranteed to have been assigned in the controller, but they are in the $onInit hook.
2539 DatePickerCtrl.prototype.$onInit = function() {
2542 * Holds locale-specific formatters, parsers, labels etc. Allows
2543 * the user to override specific ones from the $mdDateLocale provider.
2546 this.locale = this.dateLocale ? angular.extend({}, this.$mdDateLocale, this.dateLocale) : this.$mdDateLocale;
2548 this.installPropertyInterceptors();
2549 this.attachChangeListeners();
2550 this.attachInteractionListeners();
2554 * Sets up the controller's reference to ngModelController and
2555 * applies Angular's `input[type="date"]` directive.
2556 * @param {!angular.NgModelController} ngModelCtrl Instance of the ngModel controller.
2557 * @param {Object} mdInputContainer Instance of the mdInputContainer controller.
2558 * @param {Object} inputDirective Config for Angular's `input` directive.
2560 DatePickerCtrl.prototype.configureNgModel = function(ngModelCtrl, mdInputContainer, inputDirective) {
2561 this.ngModelCtrl = ngModelCtrl;
2562 this.mdInputContainer = mdInputContainer;
2564 // The input needs to be [type="date"] in order to be picked up by Angular.
2565 this.$attrs.$set('type', 'date');
2567 // Invoke the `input` directive link function, adding a stub for the element.
2568 // This allows us to re-use Angular's logic for setting the timezone via ng-model-options.
2569 // It works by calling the link function directly which then adds the proper `$parsers` and
2570 // `$formatters` to the ngModel controller.
2571 inputDirective[0].link.pre(this.$scope, {
2575 }, this.$attrs, [ngModelCtrl]);
2579 // Responds to external changes to the model value.
2580 self.ngModelCtrl.$formatters.push(function(value) {
2581 if (value && !(value instanceof Date)) {
2582 throw Error('The ng-model for md-datepicker must be a Date instance. ' +
2583 'Currently the model is a: ' + (typeof value));
2586 self.onExternalChange(value);
2591 // Responds to external error state changes (e.g. ng-required based on another input).
2592 ngModelCtrl.$viewChangeListeners.unshift(angular.bind(this, this.updateErrorState));
2594 // Forwards any events from the input to the root element. This is necessary to get `updateOn`
2595 // working for events that don't bubble (e.g. 'blur') since Angular binds the handlers to
2596 // the `<md-datepicker>`.
2597 var updateOn = self.$mdUtil.getModelOption(ngModelCtrl, 'updateOn');
2600 this.ngInputElement.on(
2602 angular.bind(this.$element, this.$element.triggerHandler, updateOn)
2608 * Attach event listeners for both the text input and the md-calendar.
2609 * Events are used instead of ng-model so that updates don't infinitely update the other
2610 * on a change. This should also be more performant than using a $watch.
2612 DatePickerCtrl.prototype.attachChangeListeners = function() {
2615 self.$scope.$on('md-calendar-change', function(event, date) {
2616 self.setModelValue(date);
2617 self.onExternalChange(date);
2618 self.closeCalendarPane();
2621 self.ngInputElement.on('input', angular.bind(self, self.resizeInputElement));
2623 var debounceInterval = angular.isDefined(this.debounceInterval) ?
2624 this.debounceInterval : DEFAULT_DEBOUNCE_INTERVAL;
2625 self.ngInputElement.on('input', self.$mdUtil.debounce(self.handleInputEvent,
2626 debounceInterval, self));
2629 /** Attach event listeners for user interaction. */
2630 DatePickerCtrl.prototype.attachInteractionListeners = function() {
2632 var $scope = this.$scope;
2633 var keyCodes = this.$mdConstant.KEY_CODE;
2635 // Add event listener through angular so that we can triggerHandler in unit tests.
2636 self.ngInputElement.on('keydown', function(event) {
2637 if (event.altKey && event.keyCode == keyCodes.DOWN_ARROW) {
2638 self.openCalendarPane(event);
2643 if (self.openOnFocus) {
2644 self.ngInputElement.on('focus', angular.bind(self, self.openCalendarPane));
2645 angular.element(self.$window).on('blur', self.windowBlurHandler);
2647 $scope.$on('$destroy', function() {
2648 angular.element(self.$window).off('blur', self.windowBlurHandler);
2652 $scope.$on('md-calendar-close', function() {
2653 self.closeCalendarPane();
2658 * Capture properties set to the date-picker and imperitively handle internal changes.
2659 * This is done to avoid setting up additional $watches.
2661 DatePickerCtrl.prototype.installPropertyInterceptors = function() {
2664 if (this.$attrs.ngDisabled) {
2665 // The expression is to be evaluated against the directive element's scope and not
2666 // the directive's isolate scope.
2667 var scope = this.$scope.$parent;
2670 scope.$watch(this.$attrs.ngDisabled, function(isDisabled) {
2671 self.setDisabled(isDisabled);
2676 Object.defineProperty(this, 'placeholder', {
2677 get: function() { return self.inputElement.placeholder; },
2678 set: function(value) { self.inputElement.placeholder = value || ''; }
2683 * Sets whether the date-picker is disabled.
2684 * @param {boolean} isDisabled
2686 DatePickerCtrl.prototype.setDisabled = function(isDisabled) {
2687 this.isDisabled = isDisabled;
2688 this.inputElement.disabled = isDisabled;
2690 if (this.calendarButton) {
2691 this.calendarButton.disabled = isDisabled;
2696 * Sets the custom ngModel.$error flags to be consumed by ngMessages. Flags are:
2697 * - mindate: whether the selected date is before the minimum date.
2698 * - maxdate: whether the selected flag is after the maximum date.
2699 * - filtered: whether the selected date is allowed by the custom filtering function.
2700 * - valid: whether the entered text input is a valid date
2702 * The 'required' flag is handled automatically by ngModel.
2704 * @param {Date=} opt_date Date to check. If not given, defaults to the datepicker's model value.
2706 DatePickerCtrl.prototype.updateErrorState = function(opt_date) {
2707 var date = opt_date || this.date;
2709 // Clear any existing errors to get rid of anything that's no longer relevant.
2710 this.clearErrorState();
2712 if (this.dateUtil.isValidDate(date)) {
2713 // Force all dates to midnight in order to ignore the time portion.
2714 date = this.dateUtil.createDateAtMidnight(date);
2716 if (this.dateUtil.isValidDate(this.minDate)) {
2717 var minDate = this.dateUtil.createDateAtMidnight(this.minDate);
2718 this.ngModelCtrl.$setValidity('mindate', date >= minDate);
2721 if (this.dateUtil.isValidDate(this.maxDate)) {
2722 var maxDate = this.dateUtil.createDateAtMidnight(this.maxDate);
2723 this.ngModelCtrl.$setValidity('maxdate', date <= maxDate);
2726 if (angular.isFunction(this.dateFilter)) {
2727 this.ngModelCtrl.$setValidity('filtered', this.dateFilter(date));
2730 // The date is seen as "not a valid date" if there is *something* set
2731 // (i.e.., not null or undefined), but that something isn't a valid date.
2732 this.ngModelCtrl.$setValidity('valid', date == null);
2735 angular.element(this.inputContainer).toggleClass(INVALID_CLASS, !this.ngModelCtrl.$valid);
2738 /** Clears any error flags set by `updateErrorState`. */
2739 DatePickerCtrl.prototype.clearErrorState = function() {
2740 this.inputContainer.classList.remove(INVALID_CLASS);
2741 ['mindate', 'maxdate', 'filtered', 'valid'].forEach(function(field) {
2742 this.ngModelCtrl.$setValidity(field, true);
2746 /** Resizes the input element based on the size of its content. */
2747 DatePickerCtrl.prototype.resizeInputElement = function() {
2748 this.inputElement.size = this.inputElement.value.length + EXTRA_INPUT_SIZE;
2752 * Sets the model value if the user input is a valid date.
2753 * Adds an invalid class to the input element if not.
2755 DatePickerCtrl.prototype.handleInputEvent = function() {
2756 var inputString = this.inputElement.value;
2757 var parsedDate = inputString ? this.locale.parseDate(inputString) : null;
2758 this.dateUtil.setDateTimeToMidnight(parsedDate);
2760 // An input string is valid if it is either empty (representing no date)
2761 // or if it parses to a valid date that the user is allowed to select.
2762 var isValidInput = inputString == '' || (
2763 this.dateUtil.isValidDate(parsedDate) &&
2764 this.locale.isDateComplete(inputString) &&
2765 this.isDateEnabled(parsedDate)
2768 // The datepicker's model is only updated when there is a valid input.
2770 this.setModelValue(parsedDate);
2771 this.date = parsedDate;
2774 this.updateErrorState(parsedDate);
2778 * Check whether date is in range and enabled
2779 * @param {Date=} opt_date
2780 * @return {boolean} Whether the date is enabled.
2782 DatePickerCtrl.prototype.isDateEnabled = function(opt_date) {
2783 return this.dateUtil.isDateWithinRange(opt_date, this.minDate, this.maxDate) &&
2784 (!angular.isFunction(this.dateFilter) || this.dateFilter(opt_date));
2787 /** Position and attach the floating calendar to the document. */
2788 DatePickerCtrl.prototype.attachCalendarPane = function() {
2789 var calendarPane = this.calendarPane;
2790 var body = document.body;
2792 calendarPane.style.transform = '';
2793 this.$element.addClass(OPEN_CLASS);
2794 this.mdInputContainer && this.mdInputContainer.element.addClass(OPEN_CLASS);
2795 angular.element(body).addClass('md-datepicker-is-showing');
2797 var elementRect = this.inputContainer.getBoundingClientRect();
2798 var bodyRect = body.getBoundingClientRect();
2800 if (!this.topMargin || this.topMargin < 0) {
2801 this.topMargin = (this.inputMask.parent().prop('clientHeight') - this.ngInputElement.prop('clientHeight')) / 2;
2804 // Check to see if the calendar pane would go off the screen. If so, adjust position
2805 // accordingly to keep it within the viewport.
2806 var paneTop = elementRect.top - bodyRect.top - this.topMargin;
2807 var paneLeft = elementRect.left - bodyRect.left - this.leftMargin;
2809 // If ng-material has disabled body scrolling (for example, if a dialog is open),
2810 // then it's possible that the already-scrolled body has a negative top/left. In this case,
2811 // we want to treat the "real" top as (0 - bodyRect.top). In a normal scrolling situation,
2812 // though, the top of the viewport should just be the body's scroll position.
2813 var viewportTop = (bodyRect.top < 0 && document.body.scrollTop == 0) ?
2815 document.body.scrollTop;
2817 var viewportLeft = (bodyRect.left < 0 && document.body.scrollLeft == 0) ?
2819 document.body.scrollLeft;
2821 var viewportBottom = viewportTop + this.$window.innerHeight;
2822 var viewportRight = viewportLeft + this.$window.innerWidth;
2824 // Creates an overlay with a hole the same size as element. We remove a pixel or two
2825 // on each end to make it overlap slightly. The overlay's background is added in
2826 // the theme in the form of a box-shadow with a huge spread.
2827 this.inputMask.css({
2828 position: 'absolute',
2829 left: this.leftMargin + 'px',
2830 top: this.topMargin + 'px',
2831 width: (elementRect.width - 1) + 'px',
2832 height: (elementRect.height - 2) + 'px'
2835 // If the right edge of the pane would be off the screen and shifting it left by the
2836 // difference would not go past the left edge of the screen. If the calendar pane is too
2837 // big to fit on the screen at all, move it to the left of the screen and scale the entire
2838 // element down to fit.
2839 if (paneLeft + CALENDAR_PANE_WIDTH > viewportRight) {
2840 if (viewportRight - CALENDAR_PANE_WIDTH > 0) {
2841 paneLeft = viewportRight - CALENDAR_PANE_WIDTH;
2843 paneLeft = viewportLeft;
2844 var scale = this.$window.innerWidth / CALENDAR_PANE_WIDTH;
2845 calendarPane.style.transform = 'scale(' + scale + ')';
2848 calendarPane.classList.add('md-datepicker-pos-adjusted');
2851 // If the bottom edge of the pane would be off the screen and shifting it up by the
2852 // difference would not go past the top edge of the screen.
2853 if (paneTop + CALENDAR_PANE_HEIGHT > viewportBottom &&
2854 viewportBottom - CALENDAR_PANE_HEIGHT > viewportTop) {
2855 paneTop = viewportBottom - CALENDAR_PANE_HEIGHT;
2856 calendarPane.classList.add('md-datepicker-pos-adjusted');
2859 calendarPane.style.left = paneLeft + 'px';
2860 calendarPane.style.top = paneTop + 'px';
2861 document.body.appendChild(calendarPane);
2863 // Add CSS class after one frame to trigger open animation.
2864 this.$$rAF(function() {
2865 calendarPane.classList.add('md-pane-open');
2869 /** Detach the floating calendar pane from the document. */
2870 DatePickerCtrl.prototype.detachCalendarPane = function() {
2871 this.$element.removeClass(OPEN_CLASS);
2872 this.mdInputContainer && this.mdInputContainer.element.removeClass(OPEN_CLASS);
2873 angular.element(document.body).removeClass('md-datepicker-is-showing');
2874 this.calendarPane.classList.remove('md-pane-open');
2875 this.calendarPane.classList.remove('md-datepicker-pos-adjusted');
2877 if (this.isCalendarOpen) {
2878 this.$mdUtil.enableScrolling();
2881 if (this.calendarPane.parentNode) {
2882 // Use native DOM removal because we do not want any of the
2883 // angular state of this element to be disposed.
2884 this.calendarPane.parentNode.removeChild(this.calendarPane);
2889 * Open the floating calendar pane.
2890 * @param {Event} event
2892 DatePickerCtrl.prototype.openCalendarPane = function(event) {
2893 if (!this.isCalendarOpen && !this.isDisabled && !this.inputFocusedOnWindowBlur) {
2894 this.isCalendarOpen = this.isOpen = true;
2895 this.calendarPaneOpenedFrom = event.target;
2897 // Because the calendar pane is attached directly to the body, it is possible that the
2898 // rest of the component (input, etc) is in a different scrolling container, such as
2899 // an md-content. This means that, if the container is scrolled, the pane would remain
2900 // stationary. To remedy this, we disable scrolling while the calendar pane is open, which
2901 // also matches the native behavior for things like `<select>` on Mac and Windows.
2902 this.$mdUtil.disableScrollAround(this.calendarPane);
2904 this.attachCalendarPane();
2905 this.focusCalendar();
2906 this.evalAttr('ngFocus');
2908 // Attach click listener inside of a timeout because, if this open call was triggered by a
2909 // click, we don't want it to be immediately propogated up to the body and handled.
2911 this.$mdUtil.nextTick(function() {
2912 // Use 'touchstart` in addition to click in order to work on iOS Safari, where click
2913 // events aren't propogated under most circumstances.
2914 // See http://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html
2915 self.documentElement.on('click touchstart', self.bodyClickHandler);
2918 window.addEventListener(this.windowEventName, this.windowEventHandler);
2922 /** Close the floating calendar pane. */
2923 DatePickerCtrl.prototype.closeCalendarPane = function() {
2924 if (this.isCalendarOpen) {
2927 self.detachCalendarPane();
2928 self.ngModelCtrl.$setTouched();
2929 self.evalAttr('ngBlur');
2931 self.documentElement.off('click touchstart', self.bodyClickHandler);
2932 window.removeEventListener(self.windowEventName, self.windowEventHandler);
2934 self.calendarPaneOpenedFrom.focus();
2935 self.calendarPaneOpenedFrom = null;
2937 if (self.openOnFocus) {
2938 // Ensures that all focus events have fired before resetting
2939 // the calendar. Prevents the calendar from reopening immediately
2940 // in IE when md-open-on-focus is set. Also it needs to trigger
2941 // a digest, in order to prevent issues where the calendar wasn't
2942 // showing up on the next open.
2943 self.$mdUtil.nextTick(reset);
2950 self.isCalendarOpen = self.isOpen = false;
2954 /** Gets the controller instance for the calendar in the floating pane. */
2955 DatePickerCtrl.prototype.getCalendarCtrl = function() {
2956 return angular.element(this.calendarPane.querySelector('md-calendar')).controller('mdCalendar');
2959 /** Focus the calendar in the floating pane. */
2960 DatePickerCtrl.prototype.focusCalendar = function() {
2961 // Use a timeout in order to allow the calendar to be rendered, as it is gated behind an ng-if.
2963 this.$mdUtil.nextTick(function() {
2964 self.getCalendarCtrl().focus();
2969 * Sets whether the input is currently focused.
2970 * @param {boolean} isFocused
2972 DatePickerCtrl.prototype.setFocused = function(isFocused) {
2974 this.ngModelCtrl.$setTouched();
2977 // The ng* expressions shouldn't be evaluated when mdOpenOnFocus is on,
2978 // because they also get called when the calendar is opened/closed.
2979 if (!this.openOnFocus) {
2980 this.evalAttr(isFocused ? 'ngFocus' : 'ngBlur');
2983 this.isFocused = isFocused;
2987 * Handles a click on the document body when the floating calendar pane is open.
2988 * Closes the floating calendar pane if the click is not inside of it.
2989 * @param {MouseEvent} event
2991 DatePickerCtrl.prototype.handleBodyClick = function(event) {
2992 if (this.isCalendarOpen) {
2993 var isInCalendar = this.$mdUtil.getClosest(event.target, 'md-calendar');
2995 if (!isInCalendar) {
2996 this.closeCalendarPane();
2999 this.$scope.$digest();
3004 * Handles the event when the user navigates away from the current tab. Keeps track of
3005 * whether the input was focused when the event happened, in order to prevent the calendar
3008 DatePickerCtrl.prototype.handleWindowBlur = function() {
3009 this.inputFocusedOnWindowBlur = document.activeElement === this.inputElement;
3013 * Evaluates an attribute expression against the parent scope.
3014 * @param {String} attr Name of the attribute to be evaluated.
3016 DatePickerCtrl.prototype.evalAttr = function(attr) {
3017 if (this.$attrs[attr]) {
3018 this.$scope.$parent.$eval(this.$attrs[attr]);
3023 * Sets the ng-model value by first converting the date object into a strng. Converting it
3024 * is necessary, in order to pass Angular's `input[type="date"]` validations. Angular turns
3025 * the value into a Date object afterwards, before setting it on the model.
3026 * @param {Date=} value Date to be set as the model value.
3028 DatePickerCtrl.prototype.setModelValue = function(value) {
3029 var timezone = this.$mdUtil.getModelOption(this.ngModelCtrl, 'timezone');
3030 this.ngModelCtrl.$setViewValue(this.ngDateFilter(value, 'yyyy-MM-dd', timezone));
3034 * Updates the datepicker when a model change occurred externally.
3035 * @param {Date=} value Value that was set to the model.
3037 DatePickerCtrl.prototype.onExternalChange = function(value) {
3038 var timezone = this.$mdUtil.getModelOption(this.ngModelCtrl, 'timezone');
3041 this.inputElement.value = this.locale.formatDate(value, timezone);
3042 this.mdInputContainer && this.mdInputContainer.setHasValue(!!value);
3043 this.resizeInputElement();
3044 this.updateErrorState();
3048 })(window, window.angular);