AngularJS:我能在ng-repeat中使用过滤器来分块数组吗?

3

编辑以添加明确的问题:我有一个长度为某些长度的平坦数组,我想将其放入 tr/td 类型的视图中。这可能也在 bootstrap 网格或类似的东西中。基本上,我想在一系列长度为 n 的块中显示一个平坦的数组。

在 SO 上有许多这个问题的变体,但我还没有真正看到一个好的解释:如何使它工作或为什么不能。因此,我制作了一个非常简单的示例来演示问题。它会渲染,但如果你检查日志,你会看到错误(太大而无法链接)。

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/


你想把一个数组分成4个部分,然后通过ng-repeat对它们进行遍历吗? - RaidenF
你的目标真的不太清楚。 - charlietfl
你收到的错误信息可能是由于无限循环引起的。如果你使用断点,你会发现你的过滤器一直执行直到 Angular 将其杀死。 - RaidenF
@K.Gkinis 好的,这似乎是可能的。但我不清楚为什么。(我在开头提出了一个明确的问题) - Kevin Lyda
我认为这是针对演示文稿的特定逻辑,应该使用CSS完成。 - Tamas Hegedus
3个回答

3

您可以通过使用记忆化(memoizing)您的块函数来避免无限循环。这解决了ng-repeat永远找不到正确引用并始终认为您正在返回新项目导致无限$digest的问题。

angular.module('filters', []).
  filter('chunk', function () {
​
    function cacheIt(func) {
      var cache = {};
      return function(arg, chunk_size) {
        // 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,chunk_size);
      };
    }
    
    // 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);
  });

有趣。我看到了一个类似的答案,但它假设你已经有了lodash,而我还没有。我创建了一个名为so-answer-2的分支,并在其中添加了这个。有一个问题:Angular缓存能在这里起作用吗? - Kevin Lyda
1
似乎没有正确将chunk_size传递给chunk方法。此外,缓存是基于数组作为第一个参数,而不是设置属性名称的最佳方式,我认为。 - Anuj Pandey
它可以工作,但由于全局作用域垃圾回收的原因,将cache = {};更改为var cache = {} - saike

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列宽的表格。


啊。这就是为什么另一个相似的问题中有一个“memoize”调用...好的,谢谢。虽然我不太想把它放在控制器中,但最终还是放在那里了。现在至少我知道为什么它必须在那里了。谢谢! - Kevin Lyda
你应该将分块逻辑移到一个服务中,个人认为这是正确的答案 :) - RaidenF

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>

这个东西非常好用!不要因为你不喜欢它就投反对票!相反,点赞吧!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接