Skip to content Skip to sidebar Skip to footer

How To Create Random/shuffle Filter Without Infinite Digest Loop

I would want to achieve the following: To be able to show image from array in random order. To solve this, I decided to create a filter : var app = angular.module('app'); app. f

Solution 1:

To fix the infinite digest, you need to wrap your filter in a memoize function. The best way to solve your problem is to install knuth-shuffle and lodash from npm, then use whatever module system you like to create the filter. This example is with CommonJS/browserify.

var memoize = require('lodash/function/memoize');
var shuffle = require('knuth-shuffle');

app.filter('shuffle', function() {
  returnmemoize(shuffle);
});

When creating filters this way, you may have a problem if an empty value is passed to the shuffle function. In that case, just add a check:

app.filter('shuffle', function() {
  returnmemoize(function(input) {
    if (input === undefined) { return; }
    return shuffle.apply(null, arguments);
  });
});

You can learn more about the infinite digest problem from this answer.

To re-shuffle the list, you can pass an arbitrary $scope property to the filter, then change that property when you want to re-shuffle. Either incrementing a number or using Math.random() are a good way to do this. This works because the result is cached according to the arguments passed, so passing an otherwise useless argument produces a new result.

myList | shuffle:whatever
$scope.whatever = 0;
$scope.reshuffle = function() {
  ++$scope.whatever;
  // OR$scope.whatever = Math.random();
};

Post a Comment for "How To Create Random/shuffle Filter Without Infinite Digest Loop"