Create Some Filters With Angular
First, what is a filter ?
A filter is something which will transform your data. One good example is the use of the filter ‘filter’ which will search in an array all elements which contains a part of the search. Filter is not limited to array, it is just an input, some parameters and you process your input to have a result so you can apply a filter on a string element or number or whatever. Perhaps you already try to display a date as string. With angular there is already a filter for this and you can simply write.
Let explain this a bit.
myDateis the data you want to process.
|is the instruction to say to angular I want to use a filter
dateis the filter I want to use
:the separator to give some parameters to my filter
'yyyy-MM-dd'the format of the date I want
Ok now everything is understood (I hope), we can create a new filter. I will take a simple case like just truncate a text. I would like to be able to truncate a long text with a filter. So my goal is to write this.
In this instruction I will truncate myLongText to have 100 characters and finishing with ‘…’
1 2 3 4 5
1 2 3 4 5 6 7 8 9 10 11 12
That’s all !!
I just have to create a filter and return a function with my data as first argument then all the other arguments I want and this function will return the data after processing.
This is a simple case but a filter shouldn’t be complicated. Most of filters should have only 10 lines maximum but it can be really easy to read your code after and to find problems. So if you are using Angular, use and re-use a lot filters ;)