Search code examples
arraysangularjssortingselectangularjs-ng-options

ng-options filter (range selecting)


I can't really explain properly what I want but I try to make a ng-options in angularJS work:

<select ng-options="object.id as object.name for object in objects" ng-model="selected"></select>

So the current output would be :

1950, 1951, 1952, 1953, 1954, 1955, 1956, 1957, 1958, 1959, 1960 ...

What I want to achieve is:

1950 - 1954, 1955 - 1959, .... 

So it will be displayed by every X year. Is there any way to achieve this? I tryed it with limitTo and then every 5th time + 5 but no success.

Has anyone a idea?


Solution

  • I'd personally just push that range-grouping logic into the javascript controller. Then you can bind to the array of pre-grouped ojects.

    Javascript:

    $scope.groupedObjects = [];  
    var groupDictionary = {};             //for keeping track of the existing buckets
    var bucketId = 0;
    //assuming objects is an array I prefer forEach, but a regular for loop would work
    $scope.objects.forEach(function (obj) { 
        var yearBucket = Math.floor(obj.name / 5) * 5; //puts things into 5-year buckets
        var upperBound = yearBucket + 4;               
        var bucketName = yearBucket + '-' + upperBound; //the name of the bucket
        if (!groupDictionary[bucketName])  { //check whether the bucket already exists
          groupDictionary[bucketName] = true;
          $scope.groupedObjects.push( {id: "id" + bucketId, name: bucketName} );
          bucketId += 1;
        }
    });
    

    And just use groupedObjects

    <select ng-options="object.id as object.name for object in groupedObjects" 
            ng-model="group"></select>
    

    Here's a plunker demonstrating this idea.