AngularJS > Filters

Exact or contains filter in AngularJS

How to filter based on exact match or contains characters in AngularJS?


To filter JSON data based on exact match or contains characters, we can use below approach.

In below code snippets, the <script> part is same as previous post where we have a JSON collection and controller specified.

<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;
    }]);
</script>


    <div ng-controller="ListController">
        <h3>Exact or contains filter</h3>
        Filter Username or address: <input type="text" ng-model="mysearch.$" />
        <br />Address only: <input type="text" ng-model="mysearch.address" /> <br />
        PIN : <input type="text" ng-model="mysearch.pin" />
        <p><input type="checkbox" ng-model="exact" /></p>
        <table class="table">
            <tr>
                <th>UserName</th>
                <th>Address</th>
                <th>PIN</th>
            </tr>
            <tr ng-repeat="member in Members | filter: mysearch:exact">
                <td>{{member.username}}</td>
                <td ng-bind="member.address"></td>
                <td>{{member.pin}}</td>
            </tr>
        </table>
    </div>

In the HTML block, notice the ng-model directive that are highlighted. For

  1. 1st text box, it is mysearch.$ that matches all the properties of the item in the collection.
  2. 2nd text box, it is mysearch.address that matches only the address property of the item in the collection.
  3. 3rd text box, it is mysearch.pin that matches only the pin property of the item in the collection.
  4. The Checkbox has exact that is used to instruct AngularJS whether to search for exact match or contains (if the checkbox is checked that returns true, the exact match happens else contains match happens)

Here mysearch is dynamically generated prefix for each property of the filter object.

Output

Exact or contains filter in angularjs

 Views: 28939 | Post Order: 32




Write for us






Hosting Recommendations