非幂等过滤器导致无限的 $digest 错误 [英] Non idempotent filter causing infinite $digest error

查看:17
本文介绍了非幂等过滤器导致无限的 $digest 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图了解 Angular 过滤器的本质.所以我有这个:

Trying to understand the nature of Angular filters. So I have this:

<p>RandomCase: {{ aString | randomCase }}</p>

还有这个:

.filter 'randomCase', () ->
    (input) ->
        input.replace /./g, (c) ->
            if Math.random() > 0.5 then c.toUpperCase() else c

Coffeescript 使这里的代码更简洁,JS 版本与完整示例一起在 JSFiddle 中找到:

Coffeescript makes for a cleaner code here, JS version is found in JSFiddle along with the complete example:

http://jsfiddle.net/nmakarov/5LdKV/

重点是通过将随机字母大写来装饰字符串.

The point is to decorate a string by having random letters capitalized.

它有效,但抛出10 $digest() 迭代达到.中止!"大多数时候.我认为出于某种原因,Angular 会重新运行过滤器至少两次以查看输出是否相同.如果没有,将再次运行它,直到最后两场比赛.事实上,由于过滤器的代码产生一个随机字符串,它不太可能连续重复两次.

it works, but throws "10 $digest() iterations reached. Aborting!" most of the time. I figured that for some reason Angular would re-run the filter at least twice to see that outputs are the same. And if not, will run it again until the last two matches. Indeed, since the filter's code produces a random string, it is quite unlikely it will repeat itself twice in a row.

现在问题来了:是否可以告诉 Angular 不要多次重新运行这个过滤器?我不需要在代码中观察这个过滤输出的值,所以不需要 Angular 观察变化 - 即使使用硬编码的字符串"代替 aString 变量,代码行为相同 - 达到 10 次迭代...

Now to the question: is it possible to tell Angular not to re-run this filter more than once? I do not need to observe the value of this filtered output in the code, so no need for Angular to watch the changes - even if a hardcoded "string" be used in place of an aString variable, the code behaves the same - 10 iterations reached...

而且我知道我可以将 randomizing 逻辑放在控制器中并将结果绑定到 $scope.aString 并且它会起作用 - 我试图理解过滤器的 Angular 方式.

And I know that I can put the randomizing logic in a controller and bind the result to a $scope.aString and it would just work - I'm trying to understand the Angular way of filters.

干杯.

推荐答案

没有 hack 就无法在监视表达式中使用非幂等过滤器.这是我能想到的最简单的一个,它将使过滤器具有幂等性...

There is no way to use an non-idempotent filter in a watched expression without a hack. This the simplest one that I can think of, which will make the filter idempotent...

使用记忆功能确保后续调用过滤器传递相同的参数返回相同的结果.

Use a memoizing function to ensure that subsequent calls to the filter passing the same arguments return the same result.

使用下划线的示例:

myApp.filter('randomCase', function() {
    return _.memoize(function (input) {
        console.log("random");
        return input.replace(/./g, function(c) {
            if (Math.random() > 0.5) {
                return c.toUpperCase();
            } else {
                return c;
            }
        });
    });
});

更新小提琴

这篇关于非幂等过滤器导致无限的 $digest 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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