【发布时间】:2016-08-18 18:41:12
【问题描述】:
我有一个包含 6 个对象的数组。
我有一个带有 ng-repeat 的列表,我想在其中显示这 6 个项目中的 3 个唯一项目。
每次刷新一次,它可能会拉出 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 isn’t just about the interface. It’s 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 个。我一定遗漏了一些东西。
【问题讨论】:
标签: javascript angularjs arrays