Suppose I have an array of 5000 objects (with boolean values) which I have to ng-repeat
in the template:
$scope.arr = [
{
"value": true
},
{
"value": false
},
{
"value": false
}
//and so on
]
Now, I want to filter this ng-repeated
array on the basis of a dynamic variable, say 'show_filter', which I am setting elsewhere.
If 'show_filter' is set to 'all' I want to show all the objects. If it is set to false (the boolean value) then I want to show objects with 'value' key set to false. Same goes for when 'show_filter' is set to true.
So, there are two approaches:
1. Build a custom filter:
I would write a custom filter for the filtering task like this:
filter:
app.filter('filterArr', function() {
return function(arr, show_filter) {
var filtered_arr = [];
if(show_filter != 'All') { //if show_filter is a boolean value
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; //return the entire array if show_filter is set to 'All'
}
}
})
template:
obj in arr | filterArr : show_filter
2. Write a filter function in the controller:
filter:
$scope.filterObjects = function(arr) {
var filtered_arr = [];
if($scope.show_filter != 'All') { //if $scope.show_filter is a boolean value
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; //return the entire array if show_filter is set to 'All'
}
}
template:
obj in filterObjects(arr)
Which of the above two methods will be faster? I have seen the custom filter code execute everytime for each digest loop and not only for changes made to $scope.show_filter
, which leds me to believe its quite inefficient. Although I am not sure which is faster between the two ways.