Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS filter list on sub element in array

I am trying to create a simple AngularJS filter on a list. However the element I want to filter on is a sub-element in an array.

(JSFIDDLE)

The objects:

elements = [{
    'claim': [{value:'foo'}],
    class: 'class1',
    subject: 'name1'
}, {
    'claim':  [{value:'bar'}],
    class: 'class1',
    subject: 'name2'
}, {
    'claim':  [{value:'baz'}],
    class: 'class1',
    subject: 'name2'
}, {
    'claim':  [{value:'quux'}],
    class: 'class1',
    subject: 'name3'
}];

HTML:

<tr class='claimrow' 
    data-ng-repeat='c in elements | filter:{claim[0].value:srcBoxFilter} | orderBy: "claim[0].value" '>

The order by handles the syntax "claim[0].value" but the filter does not.

This generates an error:

Error: Syntax Error: Token '[' is unexpected, expecting [:] 
at column 25 of the expression 
[elements | filter:{claim[0].value:srcBoxFilter} | orderBy: "claim[0].value"] 
starting at [[0].value:srcBoxFilter} | orderBy: "claim[0].value"].
like image 294
ed4becky Avatar asked Apr 19 '26 06:04

ed4becky


1 Answers

Interesting problem. Especially because the nested array value works for ordering but not filtering. I had a play with your JSFiddle and couldn't get anything out of the box working. You could get around this very easily by writing your own filter.

I've updated your JSFiddle to show how you could do this. The only changes I made to your code are shown below:

JavaScript

myApp.filter('byFirstClaimValue', function () {
    return function (items, filterText) {
        if(!filterText)
            return items;

        var out = [];
        for (var i = 0; i < items.length; i++) {
            if (items[i].claim[0].value.toLowerCase().indexOf(filterText.toLowerCase()) > -1) {
                out.push(items[i]);
            }
        }
        return out;
    }
});

HTML

<tr class="claimrow" data-ng-repeat="c in elements | byFirstClaimValue:srcBoxFilter | orderBy: 'claim[0].value'">
like image 80
David Spence Avatar answered Apr 20 '26 19:04

David Spence



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!