Angular Js Ng-repeat Choose Random Grouping From Array?
I have an array of 6 objects. I have a list with an ng-repeat where I want to display 3 unique items from those 6 items. One each refresh, it might pull 3 different items, but it
Solution 1:
User random and limitTo filters.
<png-repeat="i in list|orderBy:random|limitTo:3">{{i}}</p>
Solution 2:
This answer is a good start for a filter but there are problems with it (see the comments). I would delete the answer but the comments may be useful to someone in the future. My new answer is a better way to solve this problem for now.
You can use a custom filter:
.filter('randomSample', function() {
returnfunction(array, length) {
var copy = angular.copy(array);
var sample = [];
while(sample.length < length) {
var randomIndex = Math.floor(Math.random() * (copy.length));
sample.push(copy.splice(randomIndex, 1)[0]);
}
return sample;
};
})
Use it like:
<ling-repeat="item in array | randomSample:3">{{ item }}</li>
Here's an example on plnkr: http://plnkr.co/edit/NgsQlvgrCD7vLXnBC7q1?p=preview
Solution 3:
After many attempts, it looks like it is better to get the random values in your controller after the array is populated. Like so:
_this.sample = [];
var copy = angular.copy(_this.testimonials);
while(_this.sample.length < 3) {
var randomIndex = Math.floor(Math.random() * (copy.length));
_this.sample.push(copy.splice(randomIndex, 1)[0]);
}
Then just ng-repeat="user in home.sample"
Post a Comment for "Angular Js Ng-repeat Choose Random Grouping From Array?"