0

AngularJS track by index but from nested object in json

I've got json object "$scope.dayMonth" like this:

[
 {
   "month": 1,
   "maxDay": 31
 },
 {
   "month": 2,
   "maxDay": 28
 },
 {
   "month": 3,
   "maxDay": 31
 },
 etc...
]

So I want to show 31 rows depending on month day limit.

I tried something like this:

 <tr>
     <th class="text-center nowrap"  ng-repeat="item in dayMonth track by $index">
        {{item.maxDay}}
     </th>
 </tr>

I wanted efect of this:

<th class="text-center nowrap" ng-repeat="days in dayMonth track by $index">
  {{$index+1}}
</th>

But not for number of months - for number of maxDay.

I hope you will understand my thinking :P

Community
  • 1
  • 1
Kondziowsky
  • 173
  • 1
  • 14

1 Answers1

1

Use a function to create an array with 1 to N:

$scope.range = function(n) {
  return Array.from({length: n}, (v, k) => k+1);
};

Demo

angular.module("app",[])
.controller("ctrl",function($scope) {
  var vm=$scope;
  vm.dayMonth = [
     {"month": 1, "maxDay": 31},
     {"month": 2, "maxDay": 28},
     {"month": 3, "maxDay": 31},
     //etc.
  ];
  vm.range = function(n) {
      return Array.from({length: n}, (v, k) => k+1);
  };
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
    <div ng-repeat="monthHead in dayMonth">
      <h2>Month {{monthHead.month}}</h2>
      <table>
        <tr>
           <th ng-repeat="n in range(monthHead.maxDay)">{{n}}</th>
        </tr>
      </table>
    </div>
  </body>

See, Create a JavaScript array containing 1…N

georgeawg
  • 48,608
  • 13
  • 72
  • 95