Search code examples
angularjsjsonangularjs-ng-repeatangular-filters

AngularJS: Show a random json object within the next 5 event days


I have an events page that showcases many events in the area. There is a hero/banner element at the top of the page which i'm using an ng-repeat element on and limiting to 1.

What I would like to do is have 1 of the next 3 upcoming events be display in this banner. So it would be a random item that goes shown in there.

I have created a filter which generates a random number between 1 and 3 but i'm a little unsure on how to filter my json by date order and then within the date ordered array to generate my random number and pull out 1 of the top 3 in that array.

Any help appreciated and my repeat looks like this...

<div ng-repeat="event in Event.events | dateFilter:From:To | Orderby: start_time | RandomGeneratorFilter | limitTo:1/>

Solution

  • I managed to figure it out by making my above filter(RandomGeneratorFilter) do the below:

    function RandomGeneratorFilter($filter){
            return function(items,randomNum){
                var results = [];
                if(items && items.length >= 3){
                    var itemsLength = items.length;
                    results.push(items[randomNum]);
                }else if(items && items.length < 3){
                    results.push(items[0]);
                }
                return results;
            }
        }
    

    Where I pass in randomNum as my Math.floor calculation below:

    vm.featuredRandom = Math.floor(Math.random()*(2-0+1)+0);
    

    So in the end my ng-repeat looks like this:

    <div ng-repeat="event in Event.events | dateFilter:From:To | Orderby: start_time | RandomGeneratorFilter:vm.featuredRandom | limitTo:1/>