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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read