Aniket Sinha
Aniket Sinha

Reputation: 6031

Apply dynamic filters using Tags

I have a list of elements which is displayed in a table using ng-repeat. I want to apply dynamic filters which are added using Tags(ng-tags-input). This tag input generates dynamic tags which I want to use as filters.

Here is the plunk I have created. How can I use entries from these tags to create filters.

For a single element i tried

<body ng-controller="MainCtrl">
    <tags-input ng-model="tags"></tags-input>
    <p>Model: {{tags}}</p>
    <table border=1 cellpadding=10px>
        <tr ng-repeat = "t in tableData | filter:tags[0].text">
            <td>{{t.data1}}</td>
            <td>{{t.data2}}</td>
        </tr>
    </table>
</body>

but this will take only a single element. I want to apply entire entries of tags to be a filter.

I have seen other questions on SO, but they have filters applied as

<tr ng-repeat = "t in tableData | filter:{data1:someFilteData}">

Here is one of the fiddle. I am not able to apply filter from JSON Array. How can I do this?

Upvotes: 1

Views: 7385

Answers (1)

gkalpak
gkalpak

Reputation: 48211

If you want to include items that have a property-value that matches at least one of the tags, you can define your custom filter like this:

app.filter('filterByTags', function () {
    return function (items, tags) {
        var filtered = []; // Put here only items that match
        (items || []).forEach(function (item) { // Check each item
            var matches = tags.some(function (tag) {          // If there is some tag
                return (item.data1.indexOf(tag.text) > -1) || // that is a substring
                       (item.data2.indexOf(tag.text) > -1);   // of any property's value
            });                                               // we have a match
            if (matches) {           // If it matches
                filtered.push(item); // put it into the `filtered` array
            }
        });
        return filtered; // Return the array with items that match any tag
    };
});

And the use it like this:

<tr ng-repeat="t in tableData | filterByTags:tags">

See, also, this short demo.

Upvotes: 3

Related Questions