【问题标题】:ng-options filter (range selecting)ng-options 过滤器(范围选择)
【发布时间】:2015-07-17 06:32:59
【问题描述】:

我无法正确解释我想要什么,但我尝试在 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 次,但没有成功。

有人知道吗?

【问题讨论】:

  • 那么你只是想用 5 年而不是一年来填充你的 &lt;select&gt; 吗? object.id 属性会怎样?

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


【解决方案1】:

我个人只是将范围分组逻辑推送到 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 展示了这个想法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    相关资源
    最近更新 更多