У меня есть массив из 6 объектов.
У меня есть список с ng-repeat, где я хочу отображать 3 уникальных элемента из этих 6 элементов.
Каждый обновляется, он может вытащить 3 разных элемента, но это нормально, если это не так, единственное, что у 3 не может быть дубликатов между собой.
Например, если массив [red, yellow, blue, green, purple, cyan, fuchsia]
то при обновлении я мог бы получить:
red,blue,green
purple,blue,yellow
fuchsia,green,red
и т.д. Как вы можете видеть, меня не волнует, что синий появился там два раза подряд, но я никогда не должен быть red, blue, blue
.
У меня есть этот код:
<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>
и они в моем контроллере:
_this.random = function () {
return 0.5 - Math.random();
};
_this.testimonials = [
{
name: 'Sara Conklin',
title: 'SMB/SendPro UX Architect',
image: 'sara-conklin.jpg',
quote: 'Instead of inventing original solutions, we can leverage DS guidelines and components, save time, ensure great UX and promote consistency. '},
{
name: 'Jenn Church',
title: 'User Experience Designer',
image: 'jenn-church.jpg',
quote: 'The Design System has been a great tool in rapid prototyping, allowing me to get modern, on-brand interfaces put together quickly without having to start from scratch.'},
{
name: 'Peter Leeds',
title: 'Global Creative and Brand Activation',
image: 'peter-leeds.jpg',
quote: 'Design System provides the unified, consistent look needed to preserve and reinforce the integrity of our brand."'},
{
name: 'Marcy Goode',
title: 'Digital Marketing, Self Service & Content Management Leader',
image: 'marcy-goode.jpg',
quote: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iusto, ipsam, mollitia in vitae nemo aliquam.'},
{
name: 'Clarence Hempfield',
title: 'Spectrum Spatial Analyst Product Manager',
image: 'clarence.jpg',
quote: 'Design System isnt just about the interface. Its about understanding how people are expecting to interact with your technology.'},
{
name: 'Aaron Videtto',
title: 'SendSuite Tracking Online Product Manager',
image: 'aaron.jpg',
quote: 'Customers of SendSuite Tracking Online have been up and running within 10-15 minutes. We were able to do this because of the Design System.'}
];
Но это не ограничение 3, я получаю десятки.
ОК, пробовав маршрут фильтра, предложенный @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;
};
});
})();
а также
<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>
Это просто распечатывает все 6. Я должен что-то пропускать.
Пользовательские и предельные фильтры.
<p ng-repeat="i in list|orderBy:random|limitTo:3">{{i}}</p>
После многих попыток кажется, что лучше получить случайные значения в вашем контроллере после заполнения массива. Вот так:
_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]);
}
Затем просто ng-repeat="user in home.sample"
Этот ответ является хорошим началом для фильтра, но есть проблемы с ним (см. Комментарии). Я бы удалил ответ, но комментарии могут быть полезны кому-то в будущем. Мой новый ответ - лучший способ решить эту проблему.
Вы можете использовать собственный фильтр:
.filter('randomSample', function() {
return function(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;
};
})
Используйте его так:
<li ng-repeat="item in array | randomSample:3">{{ item }}</li>
Вот пример на plnkr: http://plnkr.co/edit/NgsQlvgrCD7vLXnBC7q1?p=preview
randomSample:3
просто чтобы посмотреть, работает ли он, и randomSample:3
на randomSample
в html