AngularJS:我可以使用过滤器在ng-repeat中对数组进行分块吗?

时间:2016-02-07 16:03:13

标签: javascript angularjs

编辑以添加一个明确的问题:我有一个长度有限的平面数组,我想把它放到tr / td类型的视图中?这也可能在引导网格或类似的东西中。基本上我想在一系列长度为n的块中显示一个平面数组。

这个问题有很多不同之处,但我还没有真正看到对这两个问题的一个很好的解释:如何使这项工作或为什么它不能。所以我做了一个非常simple example来证明这个问题。它会渲染,但是如果你查看日志,你会看到错误(太大而无法链接)。

的index.html:

<!DOCTYPE html>
<html lang="en-US" ng-app="rowApp">
<head><title>Angular chunks</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js" integrity="sha384-c4XWi4+MS7dBmCkPfB02+p/ExOF/ZBOfD2S4KR6mkmpBOg7IM6SUpA1KYZaVr7qE" crossorigin="anonymous"></script>
  <script src="app.js"></script>
</head>
<body>
  <table ng-controller="rowController" border="1" style="width:30%">
    <tr ng-repeat="people_chunk in people | chunk:4">
      <td ng-repeat="person in people_chunk">{{person.name}}</td>
    </td>
  </table>
</body>
</html>

app.js:

var rowApp = angular.module('rowApp', ['filters']);

angular.module('filters', []).
  filter('chunk', function () {
    return function (items, chunk_size) {
      var chunks = [];
      if (angular.isArray(items)) {
        if (isNaN(chunk_size))
          chunk_size = 4;
        for (var i = 0; i < items.length; i += chunk_size) {
          chunks.push(items.slice(i, i + chunk_size));
        }
      } else {
        console.log("items is not an array: " + angular.toJson(items));
      }
      return chunks;
    };
});

rowApp.controller('rowController',
  function ($scope, $http) {
    $http.get("/people.json")
      .then(function(response) { $scope.people = response.data; });
});

people.json:

[{"name": "a"}, {"name": "b"}, {"name": "c"}, {"name": "d"},
 {"name": "1"}, {"name": "2"}, {"name": "3"}, {"name": "4"}]

然后,您可以使用python -m SimpleHTTPServer 9000投放所有这些内容,然后转到http://localhost:9000/

3 个答案:

答案 0 :(得分:3)

通过简单地记忆你的块功能,你可以避免无限的摘要循环。这解决了ng-repeat从未找到正确引用的问题,并且总是认为你正在返回导致无限$ digest的新项目。

angular.module('filters', []).
  filter('chunk', function () {
​
    function cacheIt(func) {
      var cache = {};
      return function(arg) {
        // if the function has been called with the argument
        // short circuit and use cached value, otherwise call the
        // cached function with the argument and save it to the cache as well then return
        return cache[arg] ? cache[arg] : cache[arg] = func(arg);
      };
    }

    // unchanged from your example apart from we are no longer directly returning this   ​
    function chunk(items, chunk_size) {
      var chunks = [];
      if (angular.isArray(items)) {
        if (isNaN(chunk_size))
          chunk_size = 4;
        for (var i = 0; i < items.length; i += chunk_size) {
          chunks.push(items.slice(i, i + chunk_size));
        }
      } else {
        console.log("items is not an array: " + angular.toJson(items));
      }
      return chunks;
    }
​    // now we return the cached or memoized version of our chunk function
    // if you want to use lodash this is really easy since there is already a chunk and memoize function all above code would be removed
    // this return would simply be: return _.memoize(_.chunk);

    return cacheIt(chunk);
  });

答案 1 :(得分:2)

当过滤器将新数组实例作为切片返回时,angular ngRepeat将检测到它们已更改(因为ngRepeat在内部使用$watchCollection),并将导致无限的摘要循环。甚至还有一个问题,但自2013年以来它被放弃了:https://github.com/angular/angular.js/issues/2033

如果您将代码段更改为包含非常量表达式(例如[[x]]),则此问题仍然存在:

<div ng-repeat="a in [[x]]">
  <div ng-repeat="b in a">
  </div>
</div>

我担心您必须将分块逻辑移动到控制器中,或者使用css形成一个4宽度的表。

答案 2 :(得分:0)

也许这对某人有用,你永远不会知道

以下代码将为存储数组分配一个额外值(store_chunk)。所以我可以使用ng-repeat在我的HTML中显示3个不同的列

        var x               = 0;
        var y               = 1;
        var how_many_chunks = 3;
        var limit = $scope.main.stores.length / how_many_chunks ;
        angular.forEach($scope.main.stores, function(e, key) {
            if (x <= limit) {
                $scope.main.stores[key].store_chunk = y;
            }
            else{
                y    += 1;
                limit = y * limit;
                $scope.main.stores[key].store_chunk = y;
            }
            x += 1;
        });

这里是HTML

<div class="row">
    <div class="col-xs-12 col-sm-3 col-md-3 col-lg-3">
        <ul class="main_report">
            <li ng-repeat="store in main.stores | filter:{ store_chunk: 3 }">{{store.store_name}}</li>
        </ul>
    </div>
    <div class="col-xs-12 col-sm-3 col-md-3 col-lg-3">
        <ul class="main_report">
            <li ng-repeat="store in main.stores | filter:{ store_chunk: 3 }">{{store.store_name}}</li>
        </ul>
    </div>
    <div class="col-xs-12 col-sm-3 col-md-3 col-lg-3">
        <ul class="main_report">
            <li ng-repeat="store in main.stores | filter:{ store_chunk: 3 }">{{store.store_name}}</li>
        </ul>
    </div>
</div>

这就像一个魅力!并且不要因为你不喜欢而投票!相反,竖起大拇指!