DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • How to Create Multi-Field Data Filters in Angular
  • Why Angular and ASP.NET Core Make a Winning Team
  • jQuery vs. Angular: Common Differences You Must Know
  • Angular v16: A New Era of Angular Development

Trending

  • Selecting the Right Automated Tests
  • Demystifying Enterprise Integration Patterns: Bridging the Gap Between Systems
  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  • Mastering Persistence: Why the Persistence Layer Is Crucial for Modern Java Applications
  1. DZone
  2. Coding
  3. Frameworks
  4. How to Create Custom Filters in AngularJS

How to Create Custom Filters in AngularJS

AngularJS gives us a simple API to create a custom filter. Check out this post and learn how.

Josh Anderson user avatar by
Josh Anderson
·
Dec. 05, 15 · Tutorial
Like (3)
Save
Tweet
Share
11.54K Views

Join the DZone community and get the full member experience.

Join For Free

have you ever used filters with the ng-repeat directive as shown in the listing below?

<div ng-controller="productcontroller">
<table class="table">              
<tr ng-repeat="a in products|filter:searchterm">
<td>{{a.name}}</td>
<td>{{a.price}}</td>
</tr>
</table>
</div>

if so, then you’ve used a filter in an angularjs application. angularjs provides us many in-built directives like search. if required, angularjs also allows us to create custom filters, which we’ll explore in this post.

angularjs gives us a simple api to create a custom filter. you’ll remember that we use app.controller() to create controllers and app.module() to create modules. in exactly the same way, angularjs has given us the angular.filter api to create a custom filter in angularjs.

a custom filter can be created using the following syntax:

to create a custom filter, you need to do the following steps:

  • create a filter using the app.filter by passing a custom filter name and a function as input parameters to the app.filter()

  • app.filter() will return a function

  • the returned function can take various optional input parameters

  • the returned function will have custom filter code and it will return the output.

let us start with creating a very simple custom filter. we can apply this custom filter on a string and it will return the string with each character in capital case.

myapp.filter('touppercase', function () {
return function (input)
    {
        var output = "";       
        output = input.touppercase();
        return output;
    }
})

we can use the touppercase custom filter in the view as shown the listing below:

<div ng-controller="productcontroller">
<table class="table">              
<tr ng-repeat="a in products|filter:searchterm">
<td>{{a.name|touppercase}}</td>
<td>{{a.price}}</td>
</tr>
</table>
</div>

we need to keep in mind that the name of the custom filter is case sensitive. the above created view is reading data from the controller as shown in the listing below:

myapp.controller("productcontroller", function ($scope) { 
    $scope.products = [
        { 'name': 'pen', 'price': '200' },
        { 'name': 'pencil', 'price': '400' },
        { 'name': 'book', 'price': '2400' },
        { 'name': 'ball', 'price': '400' },
        { 'name': 'eraser', 'price': '1200' },
   ];
})

now, we’ll get the product name rendered in capital case on the view as shown in the image below:

the filter we created above does not take any input parameter, but let us say we want one there. this can be done very easily.  in the above filter we are returning each character of the string in upper case. in the next filter we will pass the position and only the character at that position will be converted to capital. so, the filter which takes input parameter can be created as shown in the listing below:

myapp.filter('topositionuppercase', function () {
    return function (input,position)
    {
        var output = [];       
        var capletter = input.charat(position).touppercase();
        for (var i = 0; i < input.length; i++) {
            if (i == position) {
                output.push(capletter);
            } else {
                output.push(input[i]);
            }
        }
        output = output.join('');
        return output;
    }
})

we can use topositionuppercase custom filter in the view as shown the listing below. as you will notice, we are passing the input parameter to the custom filter using the colon.

<div ng-controller="productcontroller">
<table class="table">              
<tr ng-repeat="a in products|filter:searchterm">
<td>{{a.name|topositionuppercase:1}}</td>
<td>{{a.price}}</td>
</tr>
</table>
</div>

we will get the second letter of product name rendered in the capital case on the view as shown in the image below:

before we conclude this article, let us create a custom filter which will be applied on the collection of items. let us say from the list of products, we want to filter all the products greater than a given price. we can write this custom filter as shown in the listing below:

myapp.filter('pricegreaterthan', function () {
    return function (input, price) {
        var output = [];
        if (isnan(price)) {
            output = input;
        }
        else {
            angular.foreach(input, function (item) {
                if (item.price > price) {
                    output.push(item)
                }
            });
        }
        return output;
    }
})

we can use the custom filter on the view as shown in the listing below. we are passing the price parameter from the input type text box.

<h1>with custom filter</h1>
<div ng-controller="productcontroller">
<input type="number" class="form-control" placeholder="search here" ng-model="priceterm" />
<br/>
<table class="table">
<tr ng-repeat="b in products|pricegreaterthan:priceterm">
<td>{{b.name}}</td>
<td>{{b.price}}</td>
</tr>
</table>
</div>

with this we will get a filtered array on the view as shown in the image below:

so, there you have it–that’s how to create a custom filter! it’s easy–they’re nothing but functions that take one input and optional parameters to return a function. i hope you enjoyed reading!

Filter (software) AngularJS

Published at DZone with permission of Josh Anderson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Create Multi-Field Data Filters in Angular
  • Why Angular and ASP.NET Core Make a Winning Team
  • jQuery vs. Angular: Common Differences You Must Know
  • Angular v16: A New Era of Angular Development

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: