Angular:过滤器中的无限摘要循环 [英] Angular: infinite digest loop in filter

查看:19
本文介绍了Angular:过滤器中的无限摘要循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个自定义的 Angular 过滤器,它会随机将传递给它的输入大写.

I'm writing a custom Angular filter that randomly capitalizes the input passed to it.

代码如下:

angular.module('textFilters', []).filter('goBananas', function() {
  return function(input) {

    var str = input;
    var strlen = str.length;

    while(strlen--) if(Math.round(Math.random())) {
      str = str.substr(0,strlen) + str.charAt(strlen).toUpperCase() + str.substr(strlen+1);
    }

    return str;
  };
});

我这样称呼它:

    <a class='menu_button_news menu_button' ng-href='#/news'>
        {{"News" | goBananas}}
    </a>

它有效,但在我的控制台中我看到一个 rootScope:infdig (无限摘要) 循环.

It works, but in my console I'm seeing a rootScope:infdig (infinite digest) loop.

我在理解为什么会发生这种情况以及我可以做些什么来解决它时遇到了一些麻烦.如果我理解正确,这是因为此函数调用了 5 个以上的摘要操作.但是输入只被过滤器调用一次,对吗?

I'm having some trouble understanding why this is happening and what I can do to resolve it. If I understand correctly, this is due to the fact that there are more than 5 digest actions called by this function. But the input is only called once by the filter, right?

感谢任何帮助.

推荐答案

由于摘要将继续运行直到达到模型的一致状态或将运行 10 次迭代,因此您需要自己的算法来生成伪随机数将为相同的字符串返回相同的数字,以避免无限的摘要循环.如果算法使用字符值、字符位置和一些可配置的种子来生成数字,那将会很好.避免在此类算法中使用日期/时间参数.这是一种可能的解决方案:

Since digest will continue to run until consistent state of the model will be reached or 10 iterations will run, you need your own algorithm to generate pseudo-random numbers that will return the same numbers for the same strings in order to avoid infinite digest loop. It will be good if algorithm will use character value, character position and some configurable seed to generate numbers. Avoid using date/time parameters in such algorithm. Here is one of possible solutions:

HTML

<h1>{{ 'Hello Plunker!' | goBananas:17 }}</h1> 

JavaScript

angular.module('textFilters', []).
  filter('goBananas', function() {
    return function(input, seed) {
      seed = seed || 1;
      (input = input.split('')).forEach(function(c, i, arr) {
        arr[i] = c[(c.charCodeAt(0) + i + Math.round(seed / 3)) % 2 ? 'toUpperCase' : 'toLowerCase']();
      });
      return input.join('');
    }
  });

您可以使用 seed 参数来更改算法.例如它可能是 ngRepeat

You can play with seed parameter to change a bit an algorithm. For example it may be $index of ngRepeat

Plunker:http://plnkr.co/edit/oBSGQjVZjhaIMWNrPXRh?p=preview

这篇关于Angular:过滤器中的无限摘要循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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