AngularJs Filter Example


AngularJs Filter Example : It Selects subset of array and returns as a new array


AngularJs Filter Example with Syntax

In Html Template

{{ filter_expression | filter : expression : comparator}}

In Javascript

$filter('filter')(array, expression, comparator)

array : Input array as source

expression : Can be string, Object or function used for selecting items from array.

comparator : Used to determine the actual and Expected Value.

Let us understand with very basic example and demo.

Filter Example

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
</head>

<body>
<div ng-app="" ng-init="myData=[{name:'John',city:'New York'},
                                      {name:'Mike',city:'Florida'},
                                      {name:'Minni',city:'London'},
                                      {name:'Sefali',city:'Sydney'},
                                      {name:'Maya',city:'Peris'},
                                      {name:'Kelly',city:'Beijing'}]">

    <p>Search <input type="text" ng-model="searchstr"></p>
    <table id="searchResults">
    <tr><th>Name</th><th>City</th></tr>
    <tr ng-repeat="data in myData | filter:searchstr">
    <td>{{data.name}}</td>
    <td>{{data.city}}</td>
    </tr>
    </table>

</div>

</body>
</html>

Try it »

Note: Please Make you take proper ng-model name not any invalid name like : search-str Or search_str. Avoid dash, underscore and space in ng-model name.

The above example will look like this :

AngularJs Filter Example

AngularJs Filter Example

When we search the “Maya” keyword it show the result as below:

AngularJs result Filter Example

AngularJs Filter Example Result


Advertisements

Add Comment

📖 Read More