As I was reviewing examples in an Angular JS book, I came across a concept that has left me puzzled. It involves the use of custom filters with ng-repeat. Below are the code snippets:
<a ng-click="selectCategory()" class="btn btn-block btn-default btn-lg">
Home
</a>
<a ng-repeat="item in data.products | orderBy: 'category' | unique: 'category'" ng-click="selectCategory(item)" class="btn btn-block btn-default btn-lg">
{{item}}
</a>
The following snippet shows the controller linked to the HTML body tag.
angular.module("sportsStore").controller("sportsStoreCtrl", function ($scope) {
$scope.data = {
products: [
{
name: "Product #1",
description: "A product",
category: "Category #1",
price: 100
},
{
name: "Product #2",
description: "A product",
category: "Category #1",
price: 100
},
{
name: "Product #3",
description: "A product",
category: "Category #2",
price: 210
},
{
name: "Product #4",
description: "A product",
category: "Category #3",
price: 202
}
]
};
});
The custom filter code is as follows:
angular.module("customFilters", []).filter("unique", function () {
return function (data, propertyName) {
if (angular.isArray(data) && angular.isString(propertyName)) {
var results = [];
var keys = {};
for (var i = 0; i < data.length; i++) {
var val = data[i][propertyName];
if (angular.isUndefined(keys[val])) {
keys[val] = true;
results.push(val);
}
}
return results;
} else {
return data;
}
}
});
The purpose of the custom filter is to generate a list of categories from $scope.data.products.
Although the code works smoothly, my confusion lies in understanding the significance of "var keys = {};" within the custom filter function.
What exactly is the reason behind using the variable "keys" and setting its properties to true?