Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to Implement a Custom Filter with AngularJS?

In this tutorial, we are going to learn as to how one can develop their own customized filters in applications with the help of AngularJS. As such, we will need to use AngularJS to implement what we need to.

If you are used to developing applications, especially for the Web, you surely know the importance of a search box. Bet it on the Internet as a whole, a particular website or even just your email inbox, search boxes are used by one and all. Hence, there’s no doubting its usefulness in any application. However, one of the key aspects that search boxes take into consideration before making searches is filters. Yes, filters, like in day to day applications in the material world, separate the useful stuff from the ones that aren’t required at any time. Similarly, they find extensive use in Web based applications and developers should know how to create such filters, as per their needs and requirements, in an application. However, before we do so, we shall take a look at what AngularJS is all about.

What exactly is AngularJS?

AngularJS, or often known as just Angular, happens to be a Web application framework that was developed and is maintained by Google and also belongs to the open source community. It is mainly use to counter the many challenges that developers normally face during the development of single page Web applications. It basically simplifies the development and testing process of single page applications. This it does by providing a framework for client side architectures MVC and MVVC. It also provides various components that are very commonly used in rich Web applications.

It can also be labeled as declarative language that creates user interfaces and connects different components of software.

Using ng-repeat directive

If you have made use of ng-repeat directive to create filters, then you surely know a simple method to implement filters in an AngularJS application. AngularJS is known to provide several in-built filters, such as search. Also, as per requirements, you can also create customized filters, which what we are going to learn here in this tutorial.

Listing 1: Filter with ng-repeat directive

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

How to create custom filters?

In AngularJS, developers are provided with a very simple API that can help you build custom filters. If you have worked with AngularJS, you’d familiar with the fact that it provides app.contorller() for the creation of controllers and app.module() for the creation of modules. Using a very similar approach, AngularJS is also known to provide with an API called angular.filter that can be used for the creation of custom filters in applications.

A simple example that follows will outline the syntax to be used for the creation and implementation of a rather simple custom filter.

Listing 2: Syntax for implementing a custom filter

Myapp.filter (‘name of filter’, function () {
       return function (input, optparameter1, optparameter2)
       {
             var out;
             //code for the implementation of custom filter can be put here
             return out;
       }
})

The steps for creating a custom filter –

· The first step is the creation of a filter by the usage of app.filter. Pass a custom filter name with a function as input parameters to app.filter().

· app.filter returns a function

· This function is capable of taking many optional input parameters.

· The returned function must bear the code for the custom filter and should also return the output.

Creating a very simple custom filter

Here, we are going to create a very simple custom filter. We are going to apply a filter on a string, which will return the very same string with each character in bearing block letters.

Listing 3: Creation of a simple custom filter

Myapp.filter('toUpperCase', function () {
return function (in)
    {
        var out = "";       
        out = in.toUpperCase();
        return out;
    }
})

Now, this very same thing can also be applied in the view by making use of the toUpperCase custom filter. This has been demonstrated with another example.

Listing 4: Custom filter application in the view

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

Now, one very important thing that you should take note of out here is that the name of the custom filter is case sensitive. The view that has been created above is reading data from a controller. This has been outlined below.

Listing 5: Data from the controller

Myapp.controller("Product Controller", function ($scope) { 
    $scope.products = [
        { 'name': 'pencil', 'price': '250' },
        { 'name': 'pen', 'price': '300' },
        { 'name': 'book', 'price': '3400' },
        { 'name': 'sharpener', 'price': '100' },
        { 'name': 'bat', 'price': '7000' },
   ];
})

Figure 1: Rendering output

The custom filter defined above will render all the product names in block letters because that is what it has been asked to do.

Custom filter using parameters

Now, one thing that you might have noticed with the examples demonstrated above is that none of these have used an input parameter. However, what if your application needs to have one? This can also be very simply implemented and that is what we are going to take a look at.

In the above example, we have taken each character of the string and returned them in upper case. In the case of the next filter, we are just going to pass the position and just the character at that position will be rendered as a capital letter.

Such a filter can be created using the code listing given below.

Listing 6: Custom filter creation with an input parameter

Myapp.filter('toPositionUpperCase', function () {
    return function (in,position)
    {
        var out = [];       
        var CapLetter = in.charAt(position).toUpperCase();
        for (var j = 0; j < in.length; j++) {
            if (j == position) {
                out.push(CapLetter);
            } else {
                out.push(input[j]);
            }
        }
        out = out.join('');
        return out;
    }  })

Besides the example given above, we can also make use of the toPositionUpperCase custom filter in the view. This has been demonstrated below for your perusal. Something you will likely notice here is that we pass the input parameter to the custom filter by making use of the colon.

Listing 7: Using custom filter with input parameter in the view

<div ng-controller="Product Controller">
<table class="table">              
<tr ng-repeat="a in products|filter:searchTerm">
<td>{{a.name|toPositionUpperCase:2}}</td>
<td>{{a.price}}</td>
</tr>
</table>
</div>

Here, the third letter of every product names is rendered as the capital letter on the view.

Custom filter applied on the entire collection of items

Now, we are going to take a shot at creating a custom filter for an entire collection of items. What we shall try to implement here is filter the products that happen to be higher than a certain price. This process will be outlined in the listing that follows the paragraph.

Listing 8: Custom filter for full collection of items

Myapp.filter('priceGreaterThan', function () {
    return function (in, price) {
        var out = [];
        if (isNaN(price)) {
            out = in;
        }
        else {
            angular.forEach(in, function (item) {
                if (item.price > price) {
                    out.push(item)
                }
            });
        }
        return out;
    }
})

This custom filter, just like some of the other defined above, can also be used on the view. This is demonstrated in the listing below. We will pass the price parameter from the input type text box.

Listing 9: Custom filter on collection in the view

<h1>With Custom Filter Implementation</h1>
<div ng-controller="Product Controller">
<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>

The above code will offer a filtered array and sort out the higher than given price listings.

Figure 2: Filter output

Conclusion

As we have outlined already, filters have numerous uses in Web-based applications, such as in applications, in email boxes, and in entire websites. They are used mainly for the implementation of search functionalities in these areas that have been mentioned. AngularJS provide us with a solid application programming interface framework that has its very own in-built filters and also allows for easy implementation of custom made ones.

The above tutorial takes you right from the start, where you learn about the syntax for implementation of basic filters, to the finish. It also covers the implementation of all of these filters in the view as well. You might have noticed about how simple it is to implement these filters. Basically, these are functions that accept an input and parameters that are optional, and then return a function. Despite this they are pretty useful as we already have an idea about their uses. We hope that this tutorial will be easy to grasp and take you through the entire process for building custom filters with the use of AngularJS framework.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login