Thursday, July 2, 2015

AngularJS Custom Filters

AngularJS filters are used to format/transform the data displayed in the view, filters can be used with expressions, ng-bind, ng-repeat etc and act upon the data from the model. In the previous posts we have seen some of the key pre-defined filters, we can also create our own custom filter and use them as appropriate. In this post we shall see on how to create and use a custom filter.

Custom filters can be defined by configuring them in the application module, we will have to define a filter function, the function implementation should script the expected functionality from the filter.

The following is an example of a simple custom filter which prefix the word ‘Hello’ to any text which is annotated with the custom filter.

<html ng-app="custFilter">
    <meta charset="utf-8">
    <title>AngularJS - Basic</title>
    <script src="angular.min.js"></script>
                   angular.module('custFilter', [])
                   .filter('sayHello', function()
                             return function( input )
                                      return 'Hello ' + input;
                   {{'Harry' | sayHello}}


Notice that the filter sayHello has appended the text Hello in front of the name, this is just a simple implementation of the custom filter, we can implement complex filters as needed.

Search Flipkart Products:

No comments: