Monday, October 10, 2016

AngularJS - Filters

Filters can be used for 3 things, Format, Sort & Filter data.
  • Filters can be added to binding expressions by using the pipe character |, followed by a filter. {{ expression | filterName}} or {{ expression | filterName:parameter }}
          Example: {{ lastName | uppercase }}

  • Filters are added to directives, like ng-repeat, by using the pipe character |, followed by a filter. This is using done while sorting or filtering the data.
  • You can make your own filters by registering a new filter with your module by using function “filter”. This is known as custom filter.
Formatting Data:


Sorting Data:


Filtering Data:

The “filter” filter can only be used on arrays, and it returns an array containing only the matching items.

  • The “filter” filter can only be used on arrays, and it returns an array containing only the matching items.
  • By setting the ng-model directive on an input field, we can use the value of the input field as an expression in a filter.
  • Sorting can be implemented on table by adding the ng-click directive on the table headers.
Custom Filter:

A custom filter is a function that returns a function. Function filter is used for creating custom functions.
Example: A filter which matches employee attendance as this 1- present, 2- absent, 3- wfh, 4 - client visit. 
     angular.module("myApp", [])
                  .filter("attendance", function () {
                    return function (status) {
                       switch(status) {
                           case 1:
                                  return "Present";
                           case 2:
                                  return "Absent";
                           case 3:
                                  return "WFH";
                           case 4:
                                  return "Client Visit";
                         }
                      }
                   });
In this example, "attendance" is the filter name and "status" is the filter input. When this custom filter is being used it maps the numbers to corresponding string values.

Using custom filter:
        <td> {{employee.attendance | attendance }} </td>
The employee.attendance has one of the 4 numbers, filter attendance converts these number to its equivalent string values.

No comments:

Post a Comment