Wednesday, December 24, 2014

Custom filter in AngularJS

Custom filter is useful when we want to implement our own logic in time of iteration. Filter is angular component, which used to sort data based on certain criteria.

In this example, we will implement our own filter and we will use it to manipulate data.  Here we have implemented simple filter, which will make uppercase of input data.

var app = angular.module('myApp', []);

app.filter('makeUpper', function () {

            return function (item) {
                return item.toUpperCase();
            }

        })

The implementation is very simple , we have created myApp module and attached “makeUpper” filter with it. The function will take input string and return upper case of the string.
Now, we have to use the filter in view. Here is sample code to use.

        <input type="text" ng-model="name" />
        <div>
            {{name | makeUpper}}
        </div>


Angular allows filter associated with “|” over model data, Just we have to specify filter name. 


We are seeing that the output value is coming in uppercase.  So, this is one of the simplest example of filter in AngularJS. Let us assume another use-case.

We want to show only those strings (for example name) which are starts with particular character (say “S”).
Have a look on sample implementation.

    <script>

        var app = angular.module('myApp', []);
        app.controller('myController', function ($scope) {
           
            var persons = ["Ram", "Sourav", "Sudip"];
            $scope.names = persons;
        });
     
        app.filter('startsWithS', function () {
            return function (name) {
                if (name.substring(0, 1) == "S") {
                    alert(name);
                    return name;
                }
            }
        })
      
    </script>

We have implemented our custom logic to check whether the name starts with “S” or not.  If starts we are returning the name otherwise not.
Here is view to execute the filter.

<body ng-app="myApp">
  
    <div ng-controller="myController">

        <div ng-repeat="n in names">
            {{ n | startsWithS}}
        </div>

    </div>

</body>

Now, we are seeing that only 2 names which started with “S” are showing.



No comments:

Post a Comment