angular.js使用ng-options仅显示唯一值

Tim*_*ter 19 angularjs

如果我有一个阵列

$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light'},
{name:'red', shade:'dark'},
{name:'red', shade:'dark'},
{name:'yellow', shade:'light'}
Run Code Online (Sandbox Code Playgroud)

].

是否可以使用ng-options构建一个只有下拉列表中唯一值的select元素,因此红色只显示一次?

bml*_*ite 35

AngularUI正是你需要的,'unique'过滤器(src代码).

例:

ng-options="color in colors | unique:'name'"
Run Code Online (Sandbox Code Playgroud)

  • 或者在此示例中创建自己的:http://stackoverflow.com/a/18382680/39722 (2认同)

a8m*_*a8m 12

您可以使用angular.filter模块的uniq/unique过滤器.
用法: collection | unique: 'property'collection | unique: 'nested.property'

JS:

$scope.colors = [
 {name:'black', shade:'dark'},
 {name:'white', shade:'light'},
 {name:'red', shade:'dark'},
 {name:'red', shade:'dark'},
 {name:'yellow', shade:'light'}
];
Run Code Online (Sandbox Code Playgroud)

HTML:

<select ng-options="color in colors | unique:'name'"></select>
Run Code Online (Sandbox Code Playgroud)