Reputation: 41
I'm attempting to upgrade from Angular 1.2 to 1.4. I've encountered an issue with my date inputs as Angular now requires the value to be a Date object instead of a string. I was able to resolve this by creating a directive which converts the string value to a Date object. This works great in Chrome, however when I open my form for editing in a non HTML5 compatible browser the date doesn't display. According to the Angular documentation below my value should be displayed as long as it's in ISO format.
In browsers that do not yet support the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601 date format (yyyy-MM-dd), for example: 2009-01-06 (https://docs.angularjs.org/api/ng/input/input%5Bdate%5D)
This is my directive which works great for Chrome
.directive('formatDate', ->
require: 'ngModel'
link: (scope, elem, attr, modelCtrl) ->
modelCtrl.$formatters.push((modelValue) ->
new Date(modelValue + "CST"))
)
Tried using this in my directive instead, but it appears to return a string instead of a date so Angular throws an error
$filter('date')(modelValue, 'yyyy-MM-dd')
In my HTML I attempted to use the ng-init to initialize the value for the form as suggested in this thread, however that didn't work either.
<input class="form-control" type="date" ng-init="params.effective_date=(params.effective_date | date:'yyyy-MM-dd')" ng-model="params.effective_date" format-date />
Any help would be appreciated as I haven't been able to find any way to resolve this issue thus far.
Upvotes: 3
Views: 971
Reputation: 41
I finally figured out the problem, it was the way I was creating the date in my directive.
new Date(modelValue + "CST"))
Appending the timezone to the end of the string is supported by Chrome but not IE, Firefox and Safari. They return an Invalid Date
error.
To resolve the issue I modified my directive to add the CST
timezone offset of 5 hours to ensure the date will always be displayed in the view as 2015-10-08
. When the record is saved it will strip the time off since we don't care about it. These changes where necessary because Chrome displays the date in UTC while other browsers display it in the local timezone. For example 2015-10-08:00:00:00.000Z CST
is 2015-10-07T19:00:00.000Z UTC
. As a result the same date would be displayed on the edit form as 10/7/2015
in Chrome and 2015-10-08
in IE, Firefox, and Safari.
.directive('formatDate', ->
require: 'ngModel'
link: (scope, elem, attr, modelCtrl) ->
modelCtrl.$formatters.push((modelValue) ->
new Date(modelValue + "T05:00:00.000Z"))
modelCtrl.$parsers.push((viewValue) ->
iso_date = viewValue.toISOString()
iso_date.split("T")[0])
)
Upvotes: 1