Filter a List of Items in an Array using AngularJS filter Filter

← PrevNext →

An AngularJS filter filter will separate and return a list of items from an array of items. The new items that it returns are in the form of an array too (a new array of filtered items). It can filter an item that is either a string or an object.

While explaining the orderBy filter in a previous example, I have initialized a list of books, in an array. To explain the filter filter, I’ll use the same example, however, this time I’ll add price to each book element in the array, which will serve the values for our filter.

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
</head>

<body>
    <p>Enter some text to filter the list!</p>
    <div ng-app 

        ng-init="list=[
            { name:'Computer Architecture', price:65 }, 
            { name:'Advanced Composite Materials', price:45 }, 
            { name:'Stategies Unplugged', price:43 }, 
            { name:'Teaching Science', price:50 }, 
            { name:'Challenging Times', price:22 }]">

        <p><input type="text" ng-model="price" /></p>

        <!-- LOOP.-->
        <div ng-repeat="books in list | filter:price | orderBy:'name'">
            <div> {{ books.name + ' - ' + (books.price | currency) }} </div>    
        </div>
    </div>
</body>
</html>
Try it

AngularJS Filters

This is interesting. I have combined three AngularJS filters in one example. This method is also known as "Chaining Filters". Inside the ng-repeat directive, I have added the filter and orderBy filters, each separated by a pipe (|). Next, I have added the currency filter inside the expression.

Now it will show a list of books in alphabetical order (using orderBy filter) and it will filter the list of books based on the price that we enter in the input box.

In the array, I have declared price against each book. However, I have not mentioned any currency. To make sense for the selected prices, I have added the currency filter to the expression. You must use the braces “( )” to add the filter and the value on which the filter is assigned.

← PreviousNext →