Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular.js using ng-options to only display unique values

Tags:

angularjs

If I have an array

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

];

Is it possible to use ng-options to build a select element with only unique values in the dropdown, so red will only display once?

like image 834
Tim Webster Avatar asked Feb 07 '13 10:02

Tim Webster


People also ask

How do you use NG-options?

The ng-options directive fills a <select> element with <options>. The ng-options directive uses an array to fill the dropdown list. In many cases it would be easier to use the ng-repeat directive, but you have more flexibility when using the ng-options directive.

Can we use filter in NG-model?

The ng-repeat values can be filtered according to the ng-model in AngularJS by using the value of the input field as an expression in a filter. We can set the ng-model directive on an input field to filter ng-repeat values.

How do I set default Ng-options?

In my opinion the correct way to set a default value is to simply pre-fill your ng-model property with the value selected from your ng-options , angular does the rest. Essentially when you define the $scope property your select will bind to assign it the default value from your data array.

What does ng-repeat do?

Definition and Usage. The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object.


2 Answers

AngularUI has exactly what you need, the ´unique´ filter (src code).

Example:

ng-options="color in colors | unique:'name'"
like image 181
bmleite Avatar answered Nov 08 '22 17:11

bmleite


You can use uniq/unique filter of angular.filter module.
Usage: collection | unique: 'property' or 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>
like image 43
a8m Avatar answered Nov 08 '22 17:11

a8m