ng-options过滤器(范围选择)

时间:2015-05-06 21:54:40

标签: arrays angularjs sorting select angularjs-ng-options

我无法正确解释我的需求,但我尝试在angularJS中制作ng-options:

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

所以当前的输出是:

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

我想要实现的目标是:

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

因此它将每X年显示一次。 有没有办法实现这个目标? 我用limitTo尝试了它,然后每5次尝试+5但没有成功。

有人有想法吗?

1 个答案:

答案 0 :(得分:0)

我个人只是将范围分组逻辑推送到javascript控制器中。然后,您可以绑定到预先分组的对象数组。

使用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;
    }
});

只需使用groupedObjects

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

这里有plunker证明了这个想法。