Inside my controller, I would like to filter an array of objects. Each of these objects is a map which can contain strings as well as lists
I tried using $filter('filter')(array, function)
format but I do not know how to access the individual elements of the array inside my function. Here is a snippet to show what I want.
$filter('filter')(array, function() {
return criteriaMatch(item, criteria);
});
And then in the criteriaMatch()
, I will check if each of the individual property matches
var criteriaMatch = function(item, criteria) {
// go thro each individual property in the item and criteria
// and check if they are equal
}
I have to do all these in the controller and compile a list of lists and set them in the scope. So I do need to access the $filter('filter')
this way only. All the examples I found in the net so far have static criteria searches inside the function, they don't pass an criteria object and test against each item in the array.
You can use it like this: http://plnkr.co/edit/vtNjEgmpItqxX5fdwtPi?p=preview
Like you found,
filter
accepts predicate function which accepts item by item from the array. So, you just have to create an predicate function based on the givencriteria
.In this example,
criteriaMatch
is a function which returns a predicate function which matches the givencriteria
.template:
scope:
Here's an example of how you'd use
filter
within your AngularJS JavaScript (rather than in an HTML element).In this example, we have an array of Country records, each containing a name and a 3-character ISO code.
We want to write a function which will search through this list for a record which matches a specific 3-character code.
Here's how we'd do it without using
filter
:Yup, nothing wrong with that.
But here's how the same function would look, using
filter
:Much neater.
Remember that
filter
returns an array as a result (a list of matching records), so in this example, we'll either want to return 1 record, or NULL.Hope this helps.
Additionally, if you want to use the filter in your controller the same way you do it here:
You could do something like: