AngularJS > Filters

Custom filter function in AngularJS

How to filter JSON data using custom filter function in AngularJS?


We have already seen different types of filter in AngularJS. Here we will see how to filter JSON data collection using custom filter function in AngularJS.

In the below <script> code block we have a JSON collection stored in members variable. The same has been set into $scope.Members property in the controller. Next, we have created a custom filter function named FilterFunction that returns true/false based on whether the pin property value of each item in the collection has 'BY'.

<script>
    var members = [
            { username: 'SheoNarayan', address: 'Hyderabad', pin : '500049' },
            { username: 'Munna', address: 'Bokaro', pin: '8256598' },
            { username: 'Jay', address: 'Aurangabad', pin: '824101' },
            { username: 'Sreeni', address: 'New York', pin: 'BY-524' }
    ];

    var app = angular.module("app", []);
    app.controller("ListController", ["$scope", function ($scope) {
        $scope.Members = members;

        // custom filter function
        $scope.FilterFunction = function (item) {
            return (item.pin.indexOf('BY') >= 0);
        };

    }]);
</script>

In the HTML block below, notice the highlighted code snippet where we have FilterFunction to filter the Members data colleciton. If this function returns true for a specific item in this collection, that item is listed otherwise not.

    <div ng-controller="ListController">
        <h3>Filtering using custom filter function</h3>
        <table class="table">
            <tr>
                <th>UserName</th>
                <th>Address</th>
                <th>PIN</th>
            </tr>
            <tr ng-repeat="member in Members | filter:FilterFunction">
                <td>{{member.username}}</td>
                <td ng-bind="member.address"></td>
                <td>{{member.pin}}</td>
            </tr>
        </table>
    </div>

Output

Filter using custom filter function in AngularJS

 Views: 19938 | Post Order: 33




Write for us






Hosting Recommendations