Angular: infinite digest loop in filter

前端 未结 3 1975
别跟我提以往
别跟我提以往 2020-12-11 06:05

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

Here\'s the code:

angular.module(\'textFilters\', []).filter(\         


        
3条回答
  •  醉梦人生
    2020-12-11 06:46

    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

    {{ 'Hello Plunker!' | goBananas:17 }}

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

    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

提交回复
热议问题