I have developed two custom filters that are quite similar. The only distinction between these filters is the array they utilize. Therefore, I am considering creating a single custom filter and passing an array as a parameter to it. The arrays I intend to pass into the function are $rootScope.selectedCategories and $rootScope.selectedBrands. However, my dilemma lies in determining where to declare a variable that can be used as an argument for the filter, as demonstrated below.
<div class="productContentBox" ng-repeat="top in store.tops | categoryFilter: argument1 | orderBy: propertyName">
I attempted to create a scope variable in my controller with the following code structure. My approach was to use 'categoryArray' as the argument for the categoryFilter (thus replacing 'argument1' with 'categoryArray' in the previous code snippet). Unfortunately, this strategy did not yield the desired outcome, as I suspect the variable does not update according to the current $rootScope.selectedCategories (which is subject to change based on checkbox selections).
$scope.categoryArray = $rootScope.selectedCategories;
Below is the coding for the initial filter:
// Filter that operates based on product categories.
app.filter('categoryFilter', ['$rootScope', function($rootScope) {
return function(items) {
// Display all products if no filters are selected.
if ($rootScope.selectedCategories.length == 0 || checkOnlyFalse($rootScope.selectedCategories)) {
return items;
} else {
var filtered = [];
for (var i=0; i < items.length; i++) {
var item = items[i];
// Add products matching the filter criteria to the array.
for (var j=0; j < $rootScope.selectedCategories.length; j++)
if (item.category == $rootScope.selectedCategories[j]) {
filtered.push(item);
}
}
return filtered;
}
};
}]);
And here is the coding for the second filter:
// Filter that operates based on product brands.
app.filter('brandFilter', ['$rootScope', function($rootScope) {
return function(items) {
// Display all products if no filters are selected.
if ($rootScope.selectedBrands.length == 0 || checkOnlyFalse($rootScope.selectedBrands)) {
return items;
} else {
var filtered = [];
for (var i=0; i < items.length; i++) {
var item = items[i];
// Add products matching the filter criteria to the array.
for (var j=0; j < $rootScope.selectedBrands.length; j++)
if (item.brand == $rootScope.selectedBrands[j]) {
filtered.push(item);
}
}
return filtered;
}
};
}]);