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?
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.
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.
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.
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.
AngularUI has exactly what you need, the ´unique´ filter (src code).
Example:
ng-options="color in colors | unique:'name'"
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With