Shoaib Akhtar Shoaib Akhtar - 27 days ago 13
AngularJS Question

How to remove duplicate options from angular ui select?

Here is my angular ui select html:

<ui-select title="Select Template Directory" ng-change="searchTemplate()" theme="select2" ng-model="search_data.sub_directory" id="search_sub_directory" name="search_sub_directory" class="search_panel">
<ui-select-match allow-clear="true" placeholder="Select Template Directory">{{$select.selected.subDirectory}}</ui-select-match>
<ui-select-choices repeat="template.subDirectory as template in response_template_directories | filter: $select.search">
<span ng-bind-html="template.subDirectory | highlight: $select.search"></span>
</ui-select-choices>
</ui-select>


and here is
response_template_directories


[
{subDirectory : 1},
{subDirectory : 1},
{subDirectory : 1},
{subDirectory : 1},
{subDirectory : 1},
{subDirectory : 1},
{subDirectory : 2},
{subDirectory : 3},
]


Select list also showing duplicates

enter image description here

How can i remove these duplicates in ui select html?

Answer

Use filter unique (implement from AngularUI or import a8m/angular-filter).

<ui-select title="Select Template Directory" ng-change="searchTemplate()" theme="select2" ng-model="search_data.sub_directory" id="search_sub_directory" name="search_sub_directory" class="search_panel">
<ui-select-match allow-clear="true" placeholder="Select Template Directory">{{$select.selected.subDirectory}}</ui-select-match>
<ui-select-choices repeat="template.subDirectory as template in response_template_directories | unique: 'subDirectory' | filter: $select.search">
    <span ng-bind-html="template.subDirectory | highlight: $select.search"></span>
</ui-select-choices>

Or write your own filter with lodash:

app.filter('unique', function() {
    return function (arr, field) {
        return _.uniq(arr, function(a) { return a[field]; });
    };
});