I have a requirement to create a select
dropdown in my Angular page as shown below whose data is populated from a
column in a database . There is a possibility of duplicate values in the source
and I want to eliminate them in the dropdown list.
Using filters is the solution but there is no
filter provided by angular to achieve this. Here is the link for all the
available angular filters. Since there is no available filter we will have
to create a custom filter to achieve this . Below is the Angular
implementation for a custom unique filter taken from the old angular
repo unique-filter .
app.filter('unique', function () {
return function (items,
filterOn) {
if (filterOn ===
false) {
return items;
}
if ((filterOn ||
angular.isUndefined(filterOn)) &&
angular.isArray(items)) {
var hashCheck =
{}, newItems = [];
var
extractValueToCompare = function (item) {
if
(angular.isObject(item) && angular.isString(filterOn)) {
return item[filterOn];
} else {
return item;
}
};
angular.forEach(items, function (item) {
var
valueToCheck, isDuplicate = false;
for (var i =
0; i < newItems.length; i++) {
if
(angular.equals(extractValueToCompare(newItems[i]),
extractValueToCompare(item)))
{
isDuplicate = true;
break;
}
}
if
(!isDuplicate) {
newItems.push(item);
}
});
items =
newItems;
}
return items;
};
Usage :
Refer the link to plunker provided below to see a working demo of
this example .
Working Demo:
No comments :
Post a Comment