shuffle array in ng-repeat angular
Thx to http://bost.ocks.org/mike/shuffle/use this shuffling function:
Speciality with it is, that the input array stays bindable because the shuffling wont create a new array but instead does the shuffling on the same reference.
// -> Fisher–Yates shuffle algorithmvar shuffleArray = function(array) { var m = array.length, t, i; // While there remain elements to shuffle while (m) { // Pick a remaining element… i = Math.floor(Math.random() * m--); // And swap it with the current element. t = array[m]; array[m] = array[i]; array[i] = t; } return array;}
side note: lodash's _.shuffle(array)
does not work either because they are creating a new array which breaks binding (so a shuffled array won't trigger the model to be dirty)
To complete the answer to a working solution, following steps should do it:
- copy the function so you can use it inside your controller.
- call it in your
$http
result callback:
$http.get('json/questions.json').success(function (data) { //all questions $scope.questions = data; shuffleArray($scope.questions); ...}
I used lodash _.shuffle()
for showing products in home page randomly. It's very simple to use like below:
In home.component.ts file,
products: IProduct[] = []; constructor(private productService: ProductService) {} ngOnInit(): void { this.productService .getProducts() .subscribe((prodData: IProductsResponse) => { this.products = _.shuffle(prodData.products); console.log(this.products); }); }
In home.component.html file,
<div class="col-md-4 col-sm-6" *ngFor="let product of products let idx = index"> <div class="card my-2" *ngIf="idx <= 8"> <img [src]="product.image" alt="{{ product.title }}" width="200px" height="300px" class="card-img-top" style="cursor: pointer" (click)="selectProduct(product._id)" /> <div class="card-header"> <div class="card-title"> <p>{{ product.title.substr(0, 50) | uppercase }}</p> </div> </div> </div> </div>