angularjsangularjs-ng-repeatangularjs-ng-init

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


I have set date variable in "ng-init" directive and i want to add days to this date variable on every ng-repeat loop like below:

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


Solution

  • You can instantiate your first date in the controler like this :

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

    And add days to it in the ngRepeat like this :

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

    And if you want your date with the format mm/dd/yyyy, you need to add at the end of your ngInit :'M/d/yyyy', like this (you can take a look at the doc for more information about date format) :

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

    But if you have other things to do with dates I think it could be a good idea to take a look at 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>