我正在尝试从Angular 1.2升级到1.4。我遇到了日期输入问题,因为Angular现在要求值为Date对象而不是字符串。我能够通过创建一个将字符串值转换为Date对象的指令来解决这个问题。这在Chrome中运行良好,但是当我在非HTML5兼容浏览器中打开我的表单进行编辑时,日期不会显示。根据下面的Angular文档,我的值应该显示,只要它是ISO格式。
在尚不支持HTML5日期输入的浏览器中,将使用文本元素。在这种情况下,必须以有效的ISO-8601日期格式(yyyy-MM-dd)输入文本,例如:2009-01-06(https://docs.angularjs.org/api/ng/input/input%5Bdate%5D)
这是我的指令,适用于Chrome
.directive('formatDate', ->
require: 'ngModel'
link: (scope, elem, attr, modelCtrl) ->
modelCtrl.$formatters.push((modelValue) ->
new Date(modelValue + "CST"))
)
尝试在我的指令中使用它,但它似乎返回一个字符串而不是一个日期,因此Angular会抛出错误
$filter('date')(modelValue, 'yyyy-MM-dd')
在我的HTML中,我试图使用ng-init来初始化表格的值,如thread中所建议的那样,但这也不起作用。
<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 />
任何帮助都会受到赞赏,因为到目前为止我还没有找到解决这个问题的方法。
答案 0 :(得分:1)
我终于找到了问题,这就是我在指令中创建日期的方式。
new Date(modelValue + "CST"))
Chrome支持将时区附加到字符串末尾,但不支持IE,Firefox和Safari。他们返回Invalid Date
错误。
要解决此问题,我修改了我的指令,将CST
时区偏移量添加为5小时,以确保日期始终显示在视图中2015-10-08
。保存记录后,它会消除时间,因为我们不关心它。必要时会进行这些更改,因为Chrome会以UTC显示日期,而其他浏览器会在本地时区显示日期。例如,2015-10-08:00:00:00.000Z CST
为2015-10-07T19:00:00.000Z UTC
。因此,编辑表单上的相同日期将显示为Chrome中的10/7/2015
和IE,Firefox和Safari中的2015-10-08
。
.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])
)