1

I just started up learning AngularJS and I have no idea how to solve this problem. For example I have 4 records (car, plane, ship, train) and I only want to show 2 randomly in ng-repeat.

Examples: 1.st. plane, ship 2.nd. car, train 3.rd. train, plane

So how would syntax look like ?

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>
ewing1990
  • 47
  • 6

2 Answers2

0

I created something like this:

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>

Seems to work, no infdigest loop. You may want to add another condition in the while loop to break out so as to avoid an infinite loop.

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

SoluableNonagon
  • 11,541
  • 11
  • 53
  • 98
  • Big thnx for fast response, it works fine and it's just what I needed. – ewing1990 Nov 13 '14 at 18:25
  • as Ilan Frumer suggests, this is not a good approach as we are watching an object with ng-repeat and then modifying it with a filter. If you look at the console, you'll see that it is fired multiple times, getting inconsistent results... but if it works for you... – SoluableNonagon Nov 13 '14 at 18:29
  • @EliteOctagon as I said the rule: filters must be idempotent – Ilan Frumer Nov 13 '14 at 18:40
-2
<div ng-repeat="w in work = (work|orderBy:randomize).slice(0, 2)">

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

Demo: http://jsfiddle.net/hmx2zqex/

zs2020
  • 53,766
  • 29
  • 154
  • 219