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

时间:2013-02-07 10:09:14

标签: angularjs

如果我有一个数组

$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light'},
{name:'red', shade:'dark'},
{name:'red', shade:'dark'},
{name:'yellow', shade:'light'}

];

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

4 个答案:

答案 0 :(得分:35)

AngularUI正是你所需要的,'唯一'过滤器(src code)。

示例:

ng-options="color in colors | unique:'name'"

答案 1 :(得分: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'}
];

<强> HTML:

<select ng-options="color in colors | unique:'name'"></select>

答案 2 :(得分:1)

我没有发现上述回复有效。我做了以下事情:

以这种方式实施我的ng-options

<select ng-model="test" ng-options="cand.candidate for cand in candidates  | unique:'candidate'">
   <option value="">Select Candidate</option>
</select>

将您的模块添加到您的应用中:

var app = angular.module('phonecatApp', ['ui.unique']);

使用Bower安装Ui Utils Unique。 Link to instructions.

答案 3 :(得分:-4)

src="js/vendor/bower_components/angular-filter/dist/angular-filter.js"> 
angular.module('app', ['angular.filter'])
ng-repeat="color in colors | unique:'name'">{{color.name}}