Search code examples
javascriptangularjsng-options

Unique ng-options in Angular


I am trying to get unique results in angular ng-options on a select box.

<select ng-model="nationality" id="nationality" 
        ng-options="player as player.nationality for player in players></select>

The above code will get me all the nationality's however it show's duplicates.

<select ng-model="nationality" id="nationality" 
        ng-options="player as players | unique: 'player.nationality'"></select>

When I try this code angular throw's errors and shows me nothing in the select box.

Controller

var app = angular.module('premierLeagueDB', []);
app.controller('mainCtrl', function($scope, $http) {
$http({
    method : "GET",
    url : "api.php/clubs",
}).then(function mySucces(response) {
    $scope.clubs = response.data.club;
}, function myError(response) {
    $scope.showError = response.statusText;
});
});

Thanks.


Solution

  • I think this code will work for you :

    <select ng-model="nationality" id="nationality" ng-options="player as players | unique: 'nationality' "></select>
    

    ===EDIT===

    Based on this post , you need the third-party library to provide you the filter service, include this library in your html file.

    ==EDIT 2=== In order to demo how this works I make a working fiddle. In this fiddle I use anuglar-ui library to replace the module and it works as expected.

    In case that you only need 'ui.filters' module but not the other parts(import only necessary modules is the best practice), here is another fiddle link that only imports the unique function from the ui-filter module.