我在使用 AngularJS 格式化只读字段中的日期时遇到问题。这是我的 html 代码 -
<div class="row">
<label class="col-md-2">Date Last Login:</label>
<div class="col-md-3">
<input type="datetime" name="dateLastLogin" class="form-control" data-ng-model="loginDate" readonly />
</div>
</div>
我尝试在我的 Controller 中使用此代码对其进行格式化 -
$scope.$watch('vm.account.dateLastLogin', function(newValue) {
$scope.loginDate = $filter('date')(newValue, 'MM/DD/yyyy');
});
在 Controller 中放置一个断点,我看到该函数被调用,但没有显示任何内容。
如果我像这样保留我的 html -
<div class="row">
<label class="col-md-2">Date Last Login:</label>
<div class="col-md-3">
<input type="text" name="dateLastLogin" class="form-control" data-ng-model="vm.account.dateLastLogin" readonly />
</div>
</div>
我得到一个包含日期和时间的显示值,但未按照我需要的格式进行格式化。我错过了什么?
最佳答案
根据this答案是,W3C 从 HTML5 规范中删除了 datetime
输入类型。 date
和 datetime-local
仍然有效。
在您的示例中,丢弃格式过滤器,只需在有效的日期
输入上使用ng-model="vm.account.dateLastLogin"
,例如:
<input type="date" ng-model="vm.account.dateLastLogin" />
或
<input type="datetime-local" ng-model="vm.account.dateLastLogin" />
这些日期格式的格式正确,适合客户端浏览器区域设置。
或者,如果您实际上只想将其放在某个文本字段中,请将过滤器直接放入 ng-model
中,但仍使用有效的 Date
对象,例如:
<input type="text" ng-model="vm.account.dateLastLogin | date:'MM/dd/yyyy'" readonly />
参见this jsBin举一些例子
关于AngularJS 在只读字段中格式化日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30488645/