Open In App

How to filter by object property in AngularJS?

Last Updated : 11 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Filtering by object property in AngularJS is the concept of choosing the specific objects from the data array which is based on the individual properties. In creating a web application, this is the most common task that deals with the data that needs to be sorted and then displayed to the user. Developers like us can do this thing by using the filter function or can use other methods to perform the filtering by their properties. In this article, we will see two different approaches to filtering by object property in AngularJS.

Steps to filter by object property in AngularJS

The below steps will be followed for filtering by object property in AngularJS Applications.

Step 1: Create a new folder for the project. We are using the VSCode IDE to execute the command in the integrated terminal of VSCode.

mkdir filter-object
cd filter-object

Step 2: Create the index.html file in the newly created folder, we will have all our logic and styling code in this file. We can also create separate files for HTML, CSS, and JS:

We will understand the above concept with the help of suitable approaches & will understand its implementation through the illustration.

Using the built-in filter Method

In this approach, the users can be able to choose the object properties like Name, Age, and City, and specify the filter value to find the matching items from the array of users. The results which are filtered are shown to the user attractively. If any user is not found, then the alert message is shown to the user. In the approach, we are using the inbuilt method of ‘filter‘ to perform the object property filtering in AngularJS. This is the most simple and direct way to search and show the specific data which is based on the object properties.

Example: Below is an example that demonstrates filtering by object property in AngularJS using the inbuilt filter method.

HTML




<!DOCTYPE html>
<html ng-app="myApp">
  
<head>
    <title>
          AngularJS Object Property Filtering
      </title>
    <script src=
      </script>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            background-color: #f5f5f5;
        }
  
        h1 {
            color: green;
            margin-top: 20px;
        }
  
        h3 {
            color: #333;
        }
  
        .filter-container {
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-top: 20px;
            max-width: 400px;
            margin: 0 auto;
        }
  
        .filter-input {
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
        }
  
        .filter-input label {
            text-align: left;
            margin-right: 10px;
            font-weight: bold;
        }
  
        select,
        input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            font-size: 16px;
        }
  
        button {
            background-color: #009b08;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
  
        ul {
            list-style-type: none;
            padding: 0;
        }
  
        li {
            background-color: #f0f0f0;
            padding: 10px;
            border: 1px solid #ccc;
            margin-bottom: 5px;
        }
    </style>
</head>
  
<body ng-controller="myController">
    <h1>GeeksforGeeks</h1>
    <h3>
          Approach 1: Using Builtin Filter Method
      </h3>
    <div class="filter-container">
        <div class="filter-input">
            <label for="property">
                  Object:
              </label>
            <select ng-model="choosenObject" 
                    id="property">
                <option value="name">
                      Name
                  </option>
                <option value="age">
                      Age
                  </option>
                <option value="city">
                      City
                  </option>
            </select>
        </div>
        <div class="filter-input">
            <label for="filterValue">
                  Filter Value:
              </label>
            <input type="text" 
                   ng-model="filterValue" 
                   id="filterValue">
            <button ng-click="filterByProperty()">
                  Filter
              </button>
        </div>
        <h4>Filtered Users:</h4>
        <ul>
            <li ng-repeat="item in result">
                {{ item.name }} (Age: {{ item.age }},
                                 City: {{ item.city }})
            </li>
        </ul>
        <h4>All Users:</h4>
        <ul>
            <li ng-repeat="item in items">
                {{ item.name }} (Age: {{ item.age }},
                                 City: {{ item.city }})
            </li>
        </ul>
    </div>
  
    <script>
        var app = angular.module("myApp", []);
  
        app.controller("myController", function ($scope) {
            $scope.items = [
                { name: "Sneha", 
                  age: 28, 
                  city: "Kolkata" },
                { name: "Vikas", 
                  age: 40, 
                  city: "Chennai" },
                { name: "Neha", 
                  age: 32, 
                  city: "Mumbai" },
                { name: "Rajesh", 
                  age: 45, 
                  city: "Delhi" },
                { name: "Anjali", 
                  age: 29, 
                  city: "Bangalore" },
                { name: "Ravi", 
                  age: 38, 
                  city: "Kolkata" },
                { name: "Suman", 
                  age: 27, 
                  city: "Chennai" }
            ];
  
            $scope.choosenObject = "name";
            $scope.filterValue = "";
            $scope.result = [];
  
            $scope.filterByProperty = function () {
                if (!$scope.filterValue) {
                    alert("Please enter a filter value.");
                    return;
                }
  
                $scope.result = $scope.items.filter(function (item) {
                    if ($scope.choosenObject === "age") {
                        return item[$scope.choosenObject] == 
                              $scope.filterValue;
                    }
                    return item[$scope.choosenObject].toLowerCase() 
                      .includes($scope.filterValue.toLowerCase());
                });
  
                if ($scope.result.length === 0) {
                    alert("No matching records found.");
                }
            };
        });
    </script>
</body>
  
</html>


Output:

Filter1

Using Custom Filter in ng-options

In the below approach, we are using the Custom Filter in the ng-options directive for filtering by object property in AngularJS. Here, the users can input a county name in the text fields, and automatically the below drop-down menu dynamically filters and only shows the matching record to the user input. There is a custom filter in theng-options‘ directive to filter and display the relevant data. Here, the ng-options directive mainly populates and then filters the options in the ‘<select>‘ element dynamically.

Example: Below is an example that demonstrates filtering by object property in AngularJS using Custom Filter in the ng-options Directive.

HTML




<!DOCTYPE html>
<html ng-app="myApp">
  
<head>
    <title>
          AngularJS Custom Filter in ng-options
      </title>
    <script src=
      </script>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
        }
  
        h1 {
            color: green;
        }
  
        h3 {
            color: blue;
        }
  
        .filter-container {
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            margin-top: 20px;
        }
  
        .filter-input {
            margin-bottom: 20px;
        }
  
        .filter-input label {
            font-weight: bold;
            margin-right: 10px;
        }
  
        input[type="text"] {
            padding: 5px;
            width: 200px;
        }
  
        select {
            width: 220px;
            padding: 5px;
        }
    </style>
</head>
  
<body ng-controller="myController">
    <h1>
          GeeksforGeeks
      </h1>
    <h3>
          Approach 2: Using Custom Filter in ng-options
      </h3>
    <div class="filter-container">
        <div class="filter-input">
            <label for="countrySelect">
                  Filter by Country:
              </label>
            <input type="text" 
                   ng-model="filterText" 
                   id="filterText" 
                   placeholder="Enter country">
        </div>
        <div>
            <label for="countrySelect">
                  Select a Country:
              </label>
            <select id="countrySelect"
                    ng-model="selectedCountry"
                    ng-options=
                    "country.name for country in countries | 
                     filter: { name: filterText }">
                <option value="" 
                        style="display:none;">
                      -- Select Country --
                  </option>
            </select>
        </div>
        <div>
            <p>
                  Selected Country: {{ selectedCountry.name }}
              </p>
            <p>
                  Country Code: {{ selectedCountry.code }}
              </p>
        </div>
    </div>
  
    <script>
        var app = angular.module("myApp", []);
  
        app.controller("myController", function ($scope) {
            $scope.countries = [
                { name: "United States", code: "US" },
                { name: "Canada", code: "CA" },
                { name: "United Kingdom", code: "UK" },
                { name: "Germany", code: "DE" },
                { name: "France", code: "FR" },
                { name: "Australia", code: "AU" },
                { name: "India", code: "IN" },
                { name: "China", code: "CN" },
                { name: "Japan", code: "JP" },
                { name: "Brazil", code: "BR" }
            ];
  
            $scope.filterText = "";
            $scope.selectedCountry = {};
        });
    </script>
</body>
  
</html>


Output:

Filter2



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads