如何在 angularjs 中的每个 ng-repeat 循环中添加天数到日期变量

how to add days to date variable on every ng-repeat loop in angularjs

我在 "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

您可以像这样在控制器中实例化您的第一次约会:

$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>