I have a set of 6 unique objects in an array.
In my ng-repeat list, I want to display 3 different items from the array each time.
On each refresh, the selection may change but it's essential that the 3 items are distinct and don't repeat among themselves.
For example, if the array consists of colors like
[red, yellow, blue, green, purple, cyan, fuchsia]
, then upon refreshing, I might see:
red,blue,green
purple,blue,yellow
fuchsia,green,red
It doesn't matter if a color appears more than once consecutively, as long as there are no duplicates within the same set such as red, blue, blue
.
The code snippet I'm using is:
<ul class="ch-grid">
<li ng-repeat="user in home.testimonials|orderBy:random|limitTo: 3">
<div class="ch-item ch-img-1" style="background-image: url(assets/images/{{user.image}})">
<div class="ch-info">
<h3>{{user.quote}}</h3>
</div>
</div>
<h3 class="name">{{user.name}}</h3>
<p class="title">{{user.title}}</p>
</li>
</ul>
And in my controller:
_this.random = function () {
return 0.5 - Math.random();
};
_this.testimonials = [
// testimonial objects here
];
However, the current implementation displays more than 3 items at once instead of limiting to only 3.
Attempting a solution with a custom filter recommended by @csschapker:
(function () {
'use strict';
angular.module('pb.ds.home').filter('getThree', function () {
return function (array) {
var copy = angular.copy(array);
var sample = [];
while (sample.length < 3) {
var randomIndex = Math.floor(Math.random() * (copy.length));
sample.push(copy[randomIndex]);
}
return sample;
};
});
})();
Utilizing this filter method in the HTML:
<ul class="ch-grid">
<li ng-repeat="user in home.testimonials|filter:getThree">
<div class="ch-item ch-img-1" style="background-image: url(assets/images/{{user.image}})">
<div class="ch-info">
<h3>{{user.quote}}</h3>
</div>
</div>
<h3 class="name">{{user.name}}</h3>
<p class="title">{{user.title}}</p>
</li>
</ul>
Unfortunately, the filter is not functioning as expected and all 6 items are being displayed. There seems to be an oversight on my end.