Understanding how to implement an Angular filter to solve a problem I'm facing is proving to be quite challenging for me.
Let's take a look at a simple example of my data structure, which consists of an array of tasks:
var tasks = [
{ Title: "This is a task title",
Tags: ["Test","Tag","One","Two","Three"] },
{ Title: "Another test tag title",
Tags: ["Some", "More", "Tags"] },
{ Title: "One more, why not",
Tags: ["I","Like","Dirt"] },
{ Title: "Last one!",
Tags: ["You","Like","Dirt"] }
];
Each object in the array has an array of tags. Let's assume that each object is being displayed as a row in a table.
Upon initialization of the ng-controller on the page, I am collecting all unique tags from the tasks and storing them in a tags
array.
I then display these tags as toggle-able buttons on the page. Initially, all buttons are blue, indicating they are active (showing tasks with the respective tag). The goal is to click on a button to "toggle off" that tag, thereby filtering out tasks with that tag from the table.
This visual representation illustrates the concept - grey = "hide tasks with this tag", blue = "show tasks with this tag":
.
Clicking on a button changes its color to grey, filtering out corresponding tasks. Clicking again reverts the action, displaying tasks with that tag once more.
Is my explanation clear so far? This system may seem confusing at first glance.
In my attempts to achieve this functionality, I have experimented with the following:
ng-filter="task in filteredWithTags = (tasks | filter: { tags: arrayOfTags }"
, however, without success.
Could someone kindly direct me towards the right solution? :)
PS: Previously, I implemented a filterByTag(tag)
function in my controller, which iterated through each task and hid those matching the selected tag. While this method worked, it was deemed inefficient and unnecessary since "angular filters can handle all of that for you, and it will be more best-practicy". Hence, I am here seeking guidance on leveraging Angular's capabilities.
Any assistance would be greatly appreciated!