【问题标题】:AngularJS - Parsing ng-model to date/timeAngularJS - 将 ng-model 解析为日期/时间
【发布时间】:2017-08-03 22:37:28
【问题描述】:

Angular 有没有办法从日期/时间输入中获取字符串?目前,我有这个输入,例如:

<input class="admin-input" type="time" ng-model="newEvent.endHour"/>

我想将模型中的值显示为 HH:mm 但是,当我打印它的值时,它会显示完整的日期加上完整的时间。有没有办法只将输入中显示的字符串(HH:mm 格式)放入 ng-model 中?

提前致谢。

【问题讨论】:

标签: angularjs date time


【解决方案1】:

您可以使用角度 date 过滤器,

<input class="admin-input" type="time" ng-model="newEvent.endHour | date:'HH:mm'"/>

编辑 如果你想将它绑定到模型然后添加一个手表并在控制器内过滤它,

演示

var app = angular.module('App', []);
app.controller('myctrl', function($scope,$filter) {
  $scope.endHour = new Date();
  $scope.$watch('endHour', function(newValue) {
    $scope.endHour = $filter('date')(newValue, 'HH:mm');
  });
});
<!DOCTYPE html>
<html ng-app="App">

<head>
  <script data-require="angular.js@*" data-semver="1.2.14" src="//code.angularjs.org/1.2.14/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<div ng-app="App" ng-controller="myctrl">
  <input type="datetime" ng-model="endHour" class="form-control" />
</div>
</body>

</html>

【讨论】:

  • 您似乎无法为 ng-model 分配过滤器,它不起作用
  • 我建议您在控制器上执行此操作,除非您在表达式中显示它
  • 还是一样,它似乎总是会发送时间和日期的完整日期:2017-03-13T23:00:00.000Z(时区也不正确)
  • 你看演示了吗
  • 是的,我也是这样做的,也是这个stackoverflow.com/questions/36976716/…
猜你喜欢
  • 1970-01-01
  • 2013-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-27
相关资源
最近更新 更多