Imagine having an array containing 5000 objects with boolean values that need to be displayed using ng-repeat
in the template:
$scope.arr = [
{
"value": true
},
{
"value": false
},
{
"value": false
}
//and so on
]
The goal is to filter this array based on a dynamic variable called 'show_filter' which is set elsewhere.
If 'show_filter' is set to 'all', all objects should be displayed. If it is set to false, only objects with 'value' key set to false should be shown. The same applies when 'show_filter' is set to true.
There are two possible approaches for achieving this task:
1. Implementation of a custom filter:
A custom filter can be created for this purpose as follows:
filter:
app.filter('filterArr', function() {
return function(arr, show_filter) {
var filtered_arr = [];
if(show_filter != 'All') {
for(var i = 0; i < arr.length; i++) {
if(arr[i].value == show_filter) {
filtered_arr.push(arr[i]);
}
}
return filtered_arr;
}
else {
return arr;
}
}
})
template:
obj in arr | filterArr : show_filter
2. Creating a filter function in the controller:
filter:
$scope.filterObjects = function(arr) {
var filtered_arr = [];
if($scope.show_filter != 'All') {
for(var i = 0; i < arr.length; i++) {
if(arr[i].value == $scope.show_filter) {
filtered_arr.push(arr[i]);
}
}
return filtered_arr;
}
else {
return arr;
}
}
template:
obj in filterObjects(arr)
Which of these methods is more efficient? There seems to be a concern about the custom filter executing for each digest loop rather than just for changes in $scope.show_filter
, which may indicate inefficiency. It is unclear which method is faster between the two options presented.