角:无限消化过滤循环 [英] Angular: infinite digest loop in filter

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

问题描述

我正在写一个自定义的角度过滤器,随机大写传递给它的输入。

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

这里的code:

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;
  };
});

我把它在我看来,像这样:

I call it in my view like so:

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

它的工作原理,但在我的控制台我看到一个rootScope:infdig(无限摘要)循环。

我有一些无法理解为什么会发生什么,我能做些什么来解决这个问题。如果我理解正确,这是由于这一事实,即有超过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?

任何帮助AP preciated。

Any help appreciated.

推荐答案

由于消化将继续,直到模型一致的状态下运行会达到或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('');
    }
  });

您可以用种子参数起到改变位的算法。例如,它可能是 $指数 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

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

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