Tuesday, June 24, 2014

Column specific filter – AngularJS

Hi Guys,
Recently I started working on AngularJS.
We got a requirement that we have to filter a table specific to columns.
I thought I get something directly from internet, so I can copy, paste. But I didn’t get any :(
The options that are available in default AngularJS filters are, 
  1. Search the entire table using the given search string.
  2. Specify particular columns to search. (This looks like solving our problem. But it didn’t)
The problem in this available approach is, the filter always search the columns with AND condition.
ie., If I have 4 columns in my table say, “Id, Name, City, Country”. I can configure the filter like {name:my_search_string, city:my_search_string} to search in “name” and “city” column alone. (Leaving Id and Country)

Eg:
Sample data:
Id: 1     Name: Balaji               City: Chennai              Country: India
Id: 2     Name: Goutham       City: Kansas                 Country: America
Id: 3     Name: Dinesh            City: Dubai                   Country: UAE
Id: 4     Name: Satheesh        City: Helsinki               Country: Finland

If my_search_string = ‘b’, this configured filter search for b in Name AND in City. So it will not return any record.
But according to our requirement it should search the columns using OR condition and should return two records (which has ‘b’ in Name or in City)
Id: 1     Name: Balaji                           City: Chennai             Country: India
Id: 3     Name: Dinesh                        City: Dubai                  Country: UAE
(try it out in plunker)


This is also useful when we have hidden columns. Like, if we have 10 columns in my data and I want to display only 5 to the user.
In this case we will get weird results, as the normal filter consider all the 10 columns instead of only the visible 5 columns.

I didn’t get any filter options to solve this problem. So I tried to put lot of fixes and make it work. But my architect didn’t accept those fixes and told me to write a custom filter (my mind voice: therija elutha maatoma) which accepts the column keys as inputs and search only in that column. Finally I have written one column specific filter (after lot of googling).

Column Specific Filter:
Syntax: columnSpecificFilter: my_input_string (String): column_keys_to_search(String Array)
Eg: columnSpecificFilter: ’b’: [“name”, “city”]
You can find an example here.