Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

AngularJS Custom Filters

In last two posts AngularJS filter and AngularJS stateful filter I explained in details AngularJS filters with example, in this post I will explain how to create your own custom filter.

Custom Filters

Creating custom filters are quite easy in AngularJS, you require following some easy steps.

1.    Register a new filter factory function with your module. Internally, this uses the filterProvider.

2.    This factory function should return a new filter function which takes the input value as the first argument.

3.    Any filter arguments are passed in as additional arguments to the filter function.

4.    The filter functions should be pure function, means this functions is stateless and idempotent.

 

Example:

<body>
    <div ng-app="MyFirstCustomApp" ng-controller="MyController">
  <input ng-model="WelcomeMsg" type="text"><br>
  No filter: {{WelcomeMsg}}<br>
  Reverse: {{WelcomeMsg|reverse}}<br>
  Reverse & Result in uppercase: {{WelcomeMsg|reverse:true}}<br>
  Reverse, filtered in controller: {{filteredWelcomeMsg}}<br>
</div> 
</body>

 

<script>
    var app = angular.module('MyFirstCustomApp', []);
app.filter('reverse', function() {
  return function(input, uppercase) {
    input = input || '';
    var out = "";
    for (var i = 0; i < input.length; i++) {
      out = input.charAt(i) + out;
    }
    // conditional based on optional argument
    if (uppercase) {
      out = out.toUpperCase();
    }
    return out;
  };
})
.controller('MyController', ['$scope', 'reverseFilter', function($scope, reverseFilter) {
    $scope.WelcomeMsg = 'Welcome to CodeChef4u';
    $scope.filteredWelcomeMsg = reverseFilter($scope.WelcomeMsg);
}]);
 </script>

 

AngularJS Stateful Filter

In previous AngularJS Filter post I explained in details what are AngularJS filters with example, in this post I will explain stateful filter with sample example.

State

State is input values, properties, parameters that are set throughout application.

Stateful Filter

To crate state full filter you have to mark the filter as $stateful, which means that it will be executed one or more times during the each $digest cycle.

Syntax

myFilterFunc.$stateful = true;

Problem with stateful filters

In AngularJS developer document it is suggested avoid writing stateful filters, because the execution of those can't be optimized by Angular, which often leads to performance issues.

With statefull filter if we are not using any filter input parameter in that case Internal hidden state changes every time and due to that filter executing one or more times during the each $digest cycle and  that causes performance issues.

Corrections in Angular 1.3+

Filters in Angular 1.3 have been updated with some filter corrections and now filters are stateless by default.

 i.e. with current filter change result depends only on the input parameters and not on any kind of internal state. If input to filter is not changed then result is same again.

Whenever angular detects input value/parameter is changed then only it invoke a (stateless) filter not in every $digest cycle.

StateFul Filter Example:

<body ng-ap="myStatefulFilterApp" ng-controller="MyController">
    <div>
  Input: <input ng-model="WelcomeMessage"><br>
  Decoration: <input ng-model="decoration.symbol"><br>
  No filter: {{WelcomeMessage}}<br>
  Decorated: {{WelcomeMessage | decorate}}<br>
</div>
 
</body>
     <script>
         angular.module('myStatefulFilterApp', [])
         .filter('decorate', ['decoration', function (decoration) {
             function decorateFilter(input) {
                 return decoration.symbol + input + decoration.symbol;
             }
             decorateFilter.$stateful = true;
             return decorateFilter;
         }])
         .controller('MyController', ['$scope', 'decoration', function ($scope, decoration) {
             $scope.WelcomeMessage = 'Welcome to codechef4u.com';
             $scope.decoration = decoration;
         }])
         .value('decoration', { symbol: '*' });
    </script>

 


AngularJS Filters

What is an AngularJS filter?

AngularJS filter formats the value of an expression (i.e. user entered value, database value, Input field value) for display to the user.

Filters can be used in view templates, controllers, services, you can create your own custom filters easily.

Filter Syntax:

{{expression | filter }}

Filters with Argument:

You can create filters with arguments if required, that is allowed by AngularJS.

Syntax:

{{ expression | filter:argument1:argument2:... }} 

Filter Chaining:

Filters can be applied to the result of another filter, called as “Chaining” filters.

Syntax:

{{ expression | filter1 | filter2 | ... }} 

Filter components provided by AngularJS

Following are some filter components provided by AngularJS

Sr.No.

Name

Description

1

filter

Select subset of elements from source array and create new array based on provided criteria.

2

orderby

Orders the array by the expression predicate, or specified expression criteria.

3

Number

Formats a number as text.

4

uppercase

Converts a text to upper case text.

5

lowercase

Converts a text to lower case text.

6

currency

Formats text in a currency format.

7

date

Formats date to a string based on the requested format.

8

limitTo

a.     Allows you to create new array or string containing only a specified number of elements.

b.     The array elements are considered either from beginning or end of source (array, string, numbers), specified by the value and sign (positive or negative) of limit.

c.      If you are using input filed then its value is converted into string.

9

json

Allows you to convert a JavaScript object into JSON string.

 


Example:

in following example i used below filters 

   a. filter 
   b. uppercase 
   c. lowercase 
   d. number 
   e. date 
   f. currency 

I will explain Jason and limitTo filters in separate tutorials with example. 

<body>
    <div ng-app="myApp" ng-controller="EmployeeController">
        Id: {{Employee.id}}
        <br />
        <!--lowercase filter -->
        User Name:{{Employee.userName | lowercase}}
 
        <br />
        <!--date filter -->
        Birth Date:{{Employee.BirthDate | date:'medium' }}
 
        <br />
        <!--number filter -->
        Package:{{Employee.Package | number }}
 
        <!--upparcase filter -->
        <br />
        Name:<span ng-bind="Employee.name | uppercase"></span>
 
        <p>Designation: {{Employee.Designation}}</p>
 
        <!--currency filter -->
 
        <p>Payment: {{Employee.Payment | currency}}</p>
 
        <!--orderBy filter -->
        <ul>
            <li data-ng-repeat="myObject in Employee.Projects | orderBy:'name'">id:{{myObject.id}} name:{{myObject.name}} Team Size:{{myObject.TeamSize}}</li>
        </ul>
 
        <!--filter data using filter component disply active and suspended projects accroding to search inputs-->
 
        <label>Search: <input type="checkbox" ng-model="Employee.Projects.isActive"></label>
        <ul>
            <li data-ng-repeat="myObject in Employee.Projects | filter:Employee.Projects.isActive">id:{{myObject.id}} name:{{myObject.name}} Team Size:{{myObject.TeamSize}}</li>
        </ul>
    </div>
 
    <script>
        var app = angular.module('myApp', []);
        var dateOut = new Date('1985-04-05 12:08:15.773');
        app.controller('EmployeeController', ['$scope', function ($scope) {
            $scope.Employee = {
                id: 1,
                userName:'sKendre;',
                name: 'Shourya Kendre',
                BirthDate: dateOut,
                Package:52503.30,
                Designation: 'Team Leader',
                Payment: 700,
                Projects: [
                    { id: 1, name: 'E shop', TeamSize: 5 ,isActive:true},
                    { id: 2, name: 'Employee Notifier', TeamSize: 3, isActive: true },
                    { id: 3, name: 'CRM', TeamSize: 10, isActive: false }
                ]
            };
        }]);
 
       
    </script>
</body>

Date formats filter supports following string formats

 a. medium: equivalent to 'MMM d, y h:mm:ss a' for en_US locale (e.g. Sep 3, 2010 12:05:08 PM)

 b. short: equivalent to 'M/d/yy h:mm a' for en_US locale (e.g. 9/3/10 12:05 PM)

 c. fullDate: equivalent to 'EEEE, MMMM d, y' for en_US locale (e.g. Friday, September 3, 2010)

 d. longDate: equivalent to 'MMMM d, y' for en_US locale (e.g. September 3, 2010)

 e. mediumDate: equivalent to 'MMM d, y' for en_US locale (e.g. Sep 3, 2010)

 f. shortDate: equivalent to 'M/d/yy' for en_US locale (e.g. 9/3/10)

 g. mediumTime: equivalent to 'h:mm:ss a' for en_US locale (e.g. 12:05:08 PM)

 h. shortTime: equivalent to 'h:mm a' for en_US locale (e.g. 12:05 PM)

Syntax:

{{date_expression | date : format : timezone}}


In this post i explained AngularJS filters basic with sample example in separate post i will explain in Stateful filters and creating your own custom filters. 

Reference used:

https://angularjs.org