Skip to content
This repository was archived by the owner on Sep 5, 2024. It is now read-only.

Commit b4b9369

Browse files
cgxtinayuangao
authored andcommitted
fix(datepicker): keep reference of Date object (#10606)
Formatter of model was instantiating a new Date object even when the value was already a date object.
1 parent 15a8410 commit b4b9369

File tree

2 files changed

+18
-10
lines changed

2 files changed

+18
-10
lines changed

src/components/datepicker/js/datepickerDirective.js

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -450,18 +450,22 @@
450450

451451
// Responds to external changes to the model value.
452452
self.ngModelCtrl.$formatters.push(function(value) {
453-
var parsedValue = angular.isDefined(value) ? Date.parse(value) : null;
453+
var parsedValue = angular.isDefined(value) ? value : null;
454454

455-
// `parsedValue` is the time since epoch if valid or `NaN` if invalid.
456-
if (!isNaN(parsedValue) && angular.isNumber(parsedValue)) {
457-
value = new Date(parsedValue);
458-
}
455+
if (!(value instanceof Date)) {
456+
parsedValue = Date.parse(value);
457+
458+
// `parsedValue` is the time since epoch if valid or `NaN` if invalid.
459+
if (!isNaN(parsedValue) && angular.isNumber(parsedValue)) {
460+
value = new Date(parsedValue);
461+
}
459462

460-
if (value && !(value instanceof Date)) {
461-
throw Error(
462-
'The ng-model for md-datepicker must be a Date instance or a value ' +
463-
'that can be parsed into a date. Currently the model is of type: ' + typeof value
464-
);
463+
if (value && !(value instanceof Date)) {
464+
throw Error(
465+
'The ng-model for md-datepicker must be a Date instance or a value ' +
466+
'that can be parsed into a date. Currently the model is of type: ' + typeof value
467+
);
468+
}
465469
}
466470

467471
self.onExternalChange(value);

src/components/datepicker/js/datepickerDirective.spec.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,10 @@ describe('md-datepicker', function() {
7575
pageScope.$apply();
7676
}
7777

78+
it('should be the same date object as the initial ng-model', function() {
79+
expect(pageScope.myDate).toBe(initialDate);
80+
});
81+
7882
it('should set initial value from ng-model', function() {
7983
expect(controller.inputElement.value).toBe(dateLocale.formatDate(initialDate));
8084
});

0 commit comments

Comments
 (0)