AngularJS显示2个随机记录

时间:2014-11-13 18:01:32

标签: angularjs

我刚开始学习AngularJS,我不知道如何解决这个问题。例如,我有4条记录(汽车,飞机,轮船,火车),我只想在ng-repeat中随机显示2条。

实施例: 1.st.飞机,船 2.nd.汽车,火车 3.rd.火车,飞机

那语法怎么样?

JS:

app.controller('WorkCtrl', function($scope, $http) {

    $http.get('work.json').success(function(work) {

        $scope.work = work;

    });
});

HTML:

<div class="work" ng-controller="WorkCtrl">
    <ul class="grid">
        <li ng-repeat="work in work">
            <a href="@{{ work.link }}" target="blank_">
               <div class="background"></div>
               <h3 class="name">@{{ work.name }}</h3>
               <p class="description">@{{ work.description }}</p>
               <img ng-src="@{{ work.image_path }}">
            </a>
        </li>
    </ul>
</div>

2 个答案:

答案 0 :(得分:0)

我创造了这样的东西:

var app = angular.module("myApp", []);

app.controller('myCtrl', ['$scope', function($scope){

  $scope.records = ['plane', 'train', 'car', 'submarine'];

}]); 

app.filter('randomSelection', function(){
  return function(inputArray, numItemsToReturn){
    // assuming you pass an array, not doing checking here
    if(!inputArray)
      return inputArray;

    var numItems = inputArray.length;
    var min = 0;
    var max = numItems-1;
    var random = Math.floor(Math.random() * (max - min + 1)) + min;

    while (inputArray.length > numItemsToReturn){
      inputArray.splice(random, 1);
    }

    return inputArray;
  };
});

HTML:

<div ng-repeat="record in records | randomSelection : 2"> 
    {{record}}
</div>

似乎工作,没有infdigest循环。您可能希望在while循环中添加另一个条件以进行分解,以避免无限循环。

http://embed.plnkr.co/mJ5Q7n24uLnELSNPUB9z/script.js

答案 1 :(得分:-2)

<div ng-repeat="w in work = (work|orderBy:randomize).slice(0, 2)">

$scope.randomize = function () {
    return 0.5 - Math.random();
};

演示:http://jsfiddle.net/hmx2zqex/