19

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?

4 Answers 4

37

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

Example:

ng-options="color in colors | unique:'name'"
Sign up to request clarification or add additional context in comments.

Comments

12

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>

Comments

1

I didn't find that the above replies worked. I did the following:

Implemented my ng-options this way:

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

Add your module to your app:

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

Install just Ui Utils Unique, using Bower. Link to instructions.

Comments

-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}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.