对表格行使用ng-repeat

Dav*_*veJ 24 angularjs

我正在尝试将模型中的数据插入到模板中,但我想在每7次重复后添加一个新的表行.使用基于strign的模板,我可以使用迭代索引和模数很容易地完成它,但我无法弄清楚如何使用angular的DOM模板来做到这一点.

这是HTML:

<div ng-controller="MyCtrl">
  <table cellspacing="0" cellpadding="0">
   <colgroup span="7"></colgroup>

   <tbody>
     <tr class="days">
       <th scope="col" title="Monday">Mon</th>
       <th scope="col" title="Tuesday">Tue</th>
       <th scope="col" title="Wednesday">Wed</th>
       <th scope="col" title="Thursday">Thu</th>
       <th scope="col" title="Friday">Fri</th>
       <th scope="col" title="Saturday">Sat</th>
       <th scope="col" title="Sunday">Sun</th>
     </tr>
     <tr>
         <td ng-repeat="date in dates">
             {{ date }}
             <!-- After seven iterations a new `<tr>` should be aded -->
        </td>
     </tr>
 </tbody>
 </table>
</div>
Run Code Online (Sandbox Code Playgroud)

和它的javascript类似:

myApp = this.angular.module('myApp', []);

var monthDays = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 1516, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31];

myApp.controller('MyCtrl', function($scope) {
  return $scope.dates = monthDays;
});?
Run Code Online (Sandbox Code Playgroud)

你可以在这里查看JSFiddle中的代码:http://jsfiddle.net/3zhbB/2/

Ren*_*des 26

用日期制作$scope.dates一个数组数组.

其中的每个数组都是一行,并且行的数组中的每一天都是一天

看到这个更新的JSFiddle http://jsfiddle.net/6aqtj/1/

  • 我根据这个答案创建了一个可重复使用的过滤器:http://jsfiddle.net/interlock/qhewP/2/ (2认同)

Mar*_*cok 9

如果您希望保留范围数据(作为数组),您可以编写一个指令,并封装所有HTML生成,因此:

<div ng-controller="MyCtrl">
    <calendar></calendar>
</div>

myApp.directive('calendar', function() {
// Requires that scope contains a 'monthDays' array.
// Adds 'weeks' to scope.
return {
    restrict: 'E',
    replace: true,
    template: '<table cellspacing="0" cellpadding="0">'
    + ...
    + '<th scope="col" title="Sunday">Sun</th></tr>'
    + '<tr ng-repeat="week in weeks">'
    + '<td ng-repeat="day in week">{{day}}</td>'
    + '</tr></tbody></table>',
    link: function(scope) {
        scope.weeks = [];
        for (var i = 0; i < scope.monthDays.length; i++) {
            if (i % 7 == 0) {
                scope.weeks.push([]);
            }
            scope.weeks[scope.weeks.length-1].push(scope.monthDays[i]);
Run Code Online (Sandbox Code Playgroud)

小提琴:http://jsfiddle.net/mrajcok/dGpsr/


And*_*lin 5

您可以使用当前数据轻松完成此操作.我刚刚添加了一个简单的过滤器:http://jsfiddle.net/3zhbB/6/

然而,这并不是最好的解决方案,因为效率非常低.它必须创建一个新数组并进行大量切片.但它仍然很酷:-D

  • 我非常喜欢这个解决方案.遗憾的是,当它指向的jsfiddle是如此优雅时,SO帖子是如此简短.但是,使用underscore.js,它会变得更好:`myApp.filter('array',function(){return _.range;});` (2认同)