【问题标题】:how to add days to date variable on every ng-repeat loop in angularjs如何在angularjs中的每个ng-repeat循环上添加日期变量
【发布时间】:2017-07-25 12:02:49
【问题描述】:

我在“ng-init”指令中设置了日期变量,我想在每个 ng-repeat 循环中为这个日期变量添加天数,如下所示:

<table>
  <tr ng-repeat="n in myArr" ng-init="myDate=('07/25/2017'|date:addDays($index))">
    <td ng-bind="myDate"></td>
  </tr>
</table

【问题讨论】:

  • addDays的功能是什么?
  • 只是举例,不是函数。
  • 您的预期结果是什么?
  • 例如:我在数组中有 3 个对象。所以我希望在第一行“myDate=07/25/2017”,第二行“myDate=07/26/2017”和第三行“myDate=07/27/2017”
  • 是来自 myArr 的 25,26 和 27

标签: angularjs angularjs-ng-repeat angularjs-ng-init


【解决方案1】:

您可以像这样在控制器中实例化您的第一个日期:

$scope.firstDate = new Date('07/25/2017');

并在 ngRepeat 中添加天数,如下所示:

<tr ng-repeat="n in myArr" ng-init="myDate=(firstDate.setDate(firstDate.getDate() + 1)|date)">

如果您希望日期格式为 mm/dd/yyyy,则需要在 ngInit 末尾添加 :'M/d/yyyy',如下所示(您可以查看the doc了解有关日期格式的更多信息):

<tr ng-repeat="n in myArr" ng-init="myDate=(firstDate.setDate(firstDate.getDate() + 1)|date:'M/d/yyyy')">

但如果您有其他与日期有关的事情,我认为查看moment.js 可能是个好主意

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.firstDate = new Date('07/25/2017');
  $scope.myArr = [1, 2, 3, 4, 5];
});
<script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>

<table ng-app="plunker" ng-controller="MainCtrl">
  <tr ng-repeat="n in myArr" ng-init="myDate=(firstDate.setDate(firstDate.getDate() + 1)|date)">
    <td ng-bind="myDate"></td>
  </tr>
</table>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多