How to filter by object property in AngularJS?
Last Updated :
26 Jul, 2024
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=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
</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:
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 the 'ng-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=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
</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:
Similar Reads
How to Sort List by Date Filter in AngularJS ?
AngularJS is a feature-based JavaScript framework that uses various tools to create dynamic single-page web applications. While developing the application we have the requirement to play with the data in AngularJS and sort this list of data by a date properly in descending order. This can be done us
5 min read
How to filter an array of objects in ES6 ?
In this article, we will try to understand how we could filter out or separate certain data from the array of objects in ES6. Let us first try to understand how we could create an array of objects by following certain syntax provided by JavaScript. Table of Content Javascript Array of ObjectsJavascr
4 min read
How to select first object in object in AngularJS?
The main problem that we are dealing with is that for an object of objects reading the object of a particular index position is not as simple as a list. We cannot loop over it using ngFor as an object is not considered an iterable. The importance of this issue may arise when the data received from a
3 min read
How to apply filters to *ngFor in Angular ?
In this article, we will see How to apply filters to *ngFor in AngularJS, along with understanding their basic implementation through the examples. NgFor is used as a Structural Directive that renders each element for the given collection each element can be displayed on the page. Implementing the f
3 min read
How to Filter Multiple Values in AngularJS ?
AngularJS is one of the popular frameworks of many web developers to create dynamic single-page web applications. To make the application more and more dynamic, we can use the filtering of data feature to dynamically show the data to the user as per the input or selection. These provide a better use
6 min read
How to Filter an Array in JavaScript ?
The array.filter() method is used to filter array in JavaScript. The filter() method iterates and check every element for the given condition and returns a new array with the filtered output. Syntax const filteredArray = array.filter( callbackFunction ( element [, index [, array]])[, thisArg]);Note:
2 min read
How to iterate over Object in Angular ?
Objects consist of a set of key-value pairs, which are known as Properties. All Properties are named in JavaScript objects and the key part represents the Property name, while the value part represents the property Value. Each element(key-value pair) of the object can be utilized to perform a specif
3 min read
How to display length of filtered ng-repeat data in AngularJS ?
The task is to Display the length of filtered ng-repeat data. Here we are going to use alias expression to solve this problem. Approach: To display the length of filtered ng-repeat data we use an alias expression. We create an alias for the variable used to filter the ng-repeat data and display the
2 min read
How to bind select element to an object in Angular ?
AngularJS is a JavaScript-based framework. It can be used by adding it to an HTML page using a tag. AngularJS helps in extending the HTML attributes with the help of directives and binding of data to the HTML with expressions. An Angular service is a broad category that consists of any value, functi
4 min read
How to iterate over JSON object fetched from API in Angular ?
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. It is the replacement of the XML data exchange format. In this article, we will learn How to Iterate over JSON objects fetched from API i
3 min read