How to filter model in AngularJS?

Angularjs filters are used to filter model data.

Let's understand how to filter data from angular model using below code:

<!doctype html>
<html lang="en">
    <meta charset="utf-8">
    <title>AngularJS 1</title>

    <!-- cdn for ootstrap Links for css -->
    <link rel="stylesheet" href="" />

    <!-- Custom Stylesheet -->
    <link rel="stylesheet" href="app.css" />

    <!-- cdn for angularjs -->
    <script src=""></script>

    <!-- AngularJS Custom Modules -->
    <script src="./app.js"></script>
    <script src="./phone-list/phone-list.js"></script>
<body ng-app="phoneListApp">
    <div class="container">

In above, html file we added css files and js files related to our angular project. app.js file declares all the modules needed for our angularjs app called phoneListApp.

phone-list/phone-list.js file includes our component for directive phone-list. When application runs phone-list tag will be replaced with phone-list.html view file.

Let's take a look at our component file which includes controller, model and view:

// define phoneList module
 angular.module('phoneList', []);

 // component
    component('phoneList', {
    templateUrl: './phone-list/phone-list.html',
    controller: function PhoneListController() {
        this.phones = [
                name: 'Sony'
            }, {
                name: 'Iphone'
            }, {
                name: 'Samsung'
            }, {
                name: 'BlackBerry'

In here, we are creating phones array in our controller.

Our view file is located in ./phone-list/phone-list.html. Let's take a look at our view file:

    <li class="list-group-item">
        Search: <input ng-model="$ctrl.query">
    <li class="list-group-item" ng-repeat="phone in $ctrl.phones | filter:$ctrl.query">

Now, to our existing application we are adding one search box top of our list of phones. So that when user types the name of the phone our list for phones will filter our results.

To achieve this task we have added following code to our search text box:


This code tells angular that filter our model data with query supplied. Now, when we will update our ng-repeat tag and add a filter as shown below:

ng-repeat="phone in $ctrl.phones | filter:$ctrl.query"

Symbol | meaning you can supply output of previous command to our next command. It takes the list of phones and add filter to it.

Therefore when user types something in the search text box you see the changes in list of phones. Following will be the out put of our code.

What did we learn today?

  • AngularJS's filter function to process the input for the ngRepeat directive.
  • AngularJS binds the value of the input to the data model variable specified with ngModel and keeps the two in sync.
  • data that user types in search box bounds to $ctrl.query immediately and can filter model in no-time
  • Use of the filter "filter:"

Related Posts