使用ng-repeat创建包含1 ... N的列标题数组

时间:2018-05-19 12:25:11

标签: angularjs

AngularJS按索引跟踪,但是来自json

中的嵌套对象

我有这样的json对象“$ scope.dayMonth”:

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

所以我想根据月份限制显示31行。

我试过这样的事情:

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

我想要这样的效果:

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

但不是月数 - 对于maxDay的数量。

我希望你能理解我的想法:P

1 个答案:

答案 0 :(得分:1)

使用函数创建1到N的数组:

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

演示

&#13;
&#13;
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);
  };
})
&#13;
<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>
&#13;
&#13;
&#13;

请参阅Create a JavaScript array containing 1…N