【问题标题】:AngularJS Format date in read only fieldAngularJS在只读字段中格式化日期
【发布时间】:2015-08-09 21:41:37
【问题描述】:

我在使用 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>

我已尝试在我的控制器中使用此代码对其进行格式化 -

$scope.$watch('vm.account.dateLastLogin', function(newValue) {
    $scope.loginDate = $filter('date')(newValue, 'MM/DD/yyyy');
});

在控制器中设置一个断点,我看到函数被调用但没有显示任何内容。

如果我像这样离开我的 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>

我得到一个显示的值,其中包括日期和时间,但没有按照我的需要进行格式化。我错过了什么?

【问题讨论】:

  • 您尝试输入 type="date"?
  • 另外,MM/DD/yyyy 不是一个有效的模式(或者至少,它不会做你想要的)。而date、datetime-local等类型输入的文档说:模型必须始终是Date对象,否则Angular会抛出错误。

标签: angularjs


【解决方案1】:

根据this 的回答,W3C 从 HTML5 规范中删除了datetime 输入类型。 datedatetime-local 仍然有效。

在您的示例中,丢弃格式过滤器并简单地在有效的date 输入上使用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

【讨论】:

  • 在 ng-model 中放置过滤器会在页面上产生错误(它确实有效,但有错误),你知道为什么吗? “runner-3.35.12.min.js:1 错误:[ngModel:nonassign]...”
猜你喜欢
  • 2017-12-10
  • 2016-01-27
  • 1970-01-01
  • 2016-08-20
  • 2012-10-06
  • 2014-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多