为什么这个分组过滤角引起消化循环? [英] Why does this grouping angular filter cause a digest loop?

查看:128
本文介绍了为什么这个分组过滤角引起消化循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在同一时间显示在N项大块一堆物品。我需要大块的项目,因为该标记必须片状/网格(有每组N个项目,则对于每个产品的列的行)。这里有一个简单的尝试:

I'm trying to display a bunch of items in chunks of N items at a time. I need to chunk the items because the markup has to be tabular / gridded (there's a row for each group of N items, then a column for each item). Here's a simplified attempt:

app.filter('inGroupsOf', function () {
    return function (input, groupSize) {
        if (!input) {
            return [];
        }
        var result = [];
        for (var index = 0; index < input.length; index++) {
            var groupIndex = Math.floor(index / groupSize);
            if (!result[groupIndex]) {
                result[groupIndex] = [];
            }
            result[groupIndex].push(input[index]);
        }
        return result;
    };
});

<div ng-controller="Ctrl">
    <div ng-repeat="itemGroup in items | inGroupsOf:7">
        <span ng-repeat="item in itemGroup">{{item.name}}</span>
    </div>
</div>

(这里充分的版本: http://jsfiddle.net/bradleybuda/twhVj/3/

这导致了10 $摘要()的迭代达到了错误。我看接受的答案来这个问题但建议不要为我工作(比的摧毁过滤器,做这一切在控制器)等。有什么办法使这种NG重复工作与模板/过滤器?在控制器做感觉难看。

This results in a "10 $digest() iterations reached" error. I've looked at the accepted answer to this question but the suggestions there don't work for me (other than nuking the filter and doing this all in the controller). Is there any way to make this kind of ng-repeat work with a template / filter? Doing it in the controller feels ugly.

推荐答案

无限循环,因为在控制器线路12的发生:

The infinite loop is occurring because of line 12 in the controller:

result[groupIndex] = [];

在$消化循环没有发生,因为你正在创建一个定义的循环中的数组,而是因为你嵌套你在第8行创建了一个阵列内这些新的数组:

The $digest loop is not occurring because you are creating an array within a defined loop, but because you are nesting these new arrays within an array that you created in line 8:

var result = [];

即使您创建嵌套数组之外,也会发生同样的错误你的循环:

The same error will occur even if you create your nested array outside of your for loop:

var result = [];
    result[0] = [];

同样的事情嵌套的对象时也是如此。至于为什么发生这种情况,我不是很肯定。我读过在文档但仍然没有真正明白为什么数组或对象的嵌套导致$消化循环发生。用字符串或数字代替嵌套数组,你是金色的。

The same thing occurs with nested objects as well. As to "why" this occurs, I'm not very sure. I've read over the documentation but still don't really understand why the nesting of arrays or objects causes the $digest looping to occur. Replace the nested array with a string or a number and you're golden.

我想在这种情况下,逻辑具有搬回到控制器,并不能称为作为过滤器

I guess in this case, the logic has to move back to the controller, and not be called as a filter.

这篇关于为什么这个分组过滤角引起消化循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆