Group ng-repeat items

孤街浪徒 提交于 2019-12-03 15:01:43

You can use `ng-repeat' like this..

<div ng-controller="MyCtrl">
    <div ng-repeat="item in items">
        <span ng-switch on="$index % 3">
            <span ng-switch-when="0">
                <div class="row">
                    <div class="col-sm-4" ng-show="items[$index+0]">{{items[$index+0]}}</div>
                    <div class="col-sm-4" ng-show="items[$index+1]">{{items[$index+1]}}</div>
                    <div class="col-sm-4" ng-show="items[$index+2]">{{items[$index+2]}}</div>
                </div>
            </span>
        </span>
    </div>
</div>

Demo: http://bootply.com/86855

AFAIK there is no grouping directives in angular.

A solution is to group the data (underscore.js is good for this) and then have nested ng-repeats in the view.

You could define your own filter:

app.filter('inGroupsOf', function() {
  var memoized = {};

  return function() {
    key = Array.prototype.slice.call(arguments);
    if (typeof memoized[key] === "undefined") {
      memoized[key] = _inGroupsOf.apply(this, arguments);
    }

    return memoized[key];
  };

  function _inGroupsOf(collection, group_size) {
    var ar = [];
    var i, j;

    for (i = 0, j = -1; i < collection.length; i++) {
      if (i % group_size == 0) {
        j++;
        ar[j] = [];
      }

      ar[j].push(collection[i]);
    }

    return ar;
  }
});

It uses memoization to prevent Error: 10 $digest() iterations reached. Aborting!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!