Angular Shuffle filter

by Aimad Majdou

HTML

<div ng:app="ShuffleModule">
 <div ng-controller="ShuffleController">   <ul>
     <li ng-repeat="value in array | shuffle | limitTo:3">
           {{value}} 
       </li>
   </ul>
 </div>
    

</div>

JavaScript

var shufflemodule = angular.module('ShuffleModule', []);

shufflemodule.filter('shuffle', function() {
    var shuffledArr = [],
        shuffledLength = 0;
    return function(arr) {
        var o = arr.slice(0, arr.length);
        if (shuffledLength == arr.length) return shuffledArr;
        for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
        shuffledArr = o;
        shuffledLength = o.length;
        return o;
    };
});

function ShuffleController($scope) {
  $scope.array = [
  {
    "codeVille": 1,
    "nomVille": "Casablanca"
  },
  {
    "codeVille": 2,
    "nomVille": "Rabat"
  },
  {
    "codeVille": 3,
    "nomVille": "Tanger"
  },
  {
    "codeVille": 4,
    "nomVille": "Marrakech"
  },
  {
    "codeVille": 5,
    "nomVille": "Tetouan"
  },
  {
    "codeVille": 6,
    "nomVille": "Azilal"
  },
  {
    "codeVille": 7,
    "nomVille": "Beni Mellal"
  },
  {
    "codeVille": 8,
    "nomVille": "El Jadida"
  },
  {
    "codeVille": 9,
    "nomVille": "Agadir"
  },
  {
    "codeVille": 10,
    "nomVille": "Al Hoceima"
  },
  {
    "codeVille": 11,
    "nomVille": "Aoussered"
  },
  {
    "codeVille": 12,
    "nomVille": "Assilah"
  }
  ];
}