【问题标题】:Angular JS ng-repeat choose random grouping from array?Angular JS ng-repeat 从数组中选择随机分组?
【发布时间】: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 &amp; 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


    【解决方案1】:

    用户随机和limitTo过滤器。

    <p ng-repeat="i in list|orderBy:random|limitTo:3">{{i}}</p>
    

    【讨论】:

    • 是的,它会从您的列表中为您提供三个随机项目(每个项目来自不同的索引)。
    • 这可能是因为orderBy 过滤器实际上并没有改变你给它的数组。不过,我不是 100% 确定。
    • 我不认为仅仅说“随机”没有过滤功能来支持它
    • @Steve 是对的。在这种情况下,由于 controllerAs 语法,它看起来需要orderBy:home.random
    • orderBy,是的。 orderBy: random,没有。不在文档或我能找到的任何其他地方,除了在一些用户创建了一个名为 random 的函数的 jsfiddles 中
    【解决方案2】:

    这个答案对于过滤器来说是一个好的开始,但它存在问题(请参阅 cmets)。我会删除答案,但 cmets 将来可能对某人有用。我的新答案是目前解决此问题的更好方法。

    您可以使用自定义过滤器:

    .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

    【讨论】:

    • 我试过了,我一定是遗漏了一些东西,因为现在所有 6 个项目都打印出来了。我现在看到你的编辑了。
    • 尝试去掉长度参数并硬编码一个 3 来看看它是否有效并在 html 中将 randomSample:3 更改为 randomSample
    • 这行得通,除了它不断被应用。它会一遍又一遍地加载另外 3 个项目,而不仅仅是加载。
    • 查看我的 plnkr。那里对我来说工作得很好
    • 我让它在控制器中工作:plnkr.co/edit/fBPgxWHXSp5UUGzsIFFe?p=preview
    【解决方案3】:

    经过多次尝试,看起来最好在填充数组后在控制器中获取随机值。像这样:

    _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"

    【讨论】:

      猜你喜欢
      • 2014-01-14
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-10
      • 2018-03-28
      • 1970-01-01
      • 2017-09-16
      相关资源
      最近更新 更多