在ng-options中动态'分组'

时间:2013-10-10 14:01:07

标签: angularjs angularjs-directive

我有几个选项,我用ng-options填充。我想知道是否可以动态分组/不分组此选择。

这是一个(简化的)<select>

<select class="brand-select" 
  ng-model="selectedBrand" chosen="brandList"
  ng-options="brand as brand.name group by brand.bestseller for brand in brandList">
</select>

我希望能够在选择和此之间切换(注意,在这个中没有分组):

<select class="brand-select"
  ng-model="selectedBrand" chosen="brandList"
  ng-options="brand as brand.name for brand in brandList">
</select>

我希望将分组绑定到$ scope变量。

我尝试将select绑定到指令并动态设置ng-options attr的值,但似乎这是不可能的。

除了有两个选择并显示/隐藏其中一个之外,有关最佳方法的建议吗?

2 个答案:

答案 0 :(得分:3)

如果您使用1.4.8及以下的角度,上述4vanger的回答是正确的,请注意当使用角度1.5及以上时,您必须返回未定义的&#39;禁用分组。否则a&#34; null&#34;小组将出现。

答案 1 :(得分:1)

使用函数确定“分组依据”值 - 如果不需要分组,则返回null:

$scope.grouping = true
$scope.groupBy = function(v){return $scope.grouping ? v[0]: null}
...
<select ng-model="selected" ng-options="k group by groupBy(v) for (k,v) in friends"></select>      

http://jsfiddle.net/cWH4n/

相关问题