Drani Academy – Interview Question, Search Job, Tuitorials, Cheat Sheet, Project, eBook

Angular JS

Tutorials – Angular JS

 
Chapter 7: Filters in AngularJS

 

Filters are a powerful feature in AngularJS that allow you to format, transform, and filter data displayed in your web applications. In this chapter, we will explore filters in AngularJS, their usage, custom filter creation, and best practices for working with filters effectively.

Understanding Filters

Filters in AngularJS are used to modify the presentation of data in the view without altering the actual data in the model. They are applied to expressions and directives to format, transform, or filter data before it’s displayed in the view. Filters are especially useful when working with data that needs to be presented in a specific way, such as dates, numbers, or lists.

AngularJS provides a set of built-in filters, and you can create custom filters to suit your specific formatting needs.

Using Built-in Filters

AngularJS includes a variety of built-in filters that can be applied to expressions or directives. Some common built-in filters include:

  1. currency: Formats a number as currency (e.g., $1,234.56).
  2. date: Formats a date according to a specified format (e.g., ‘MM/dd/yyyy’).
  3. uppercase: Converts a string to uppercase.
  4. lowercase: Converts a string to lowercase.
  5. number: Formats a number (e.g., 1,234.56).
  6. filter: Filters an array based on a specified criteria.
  7. orderBy: Orders an array by a specified property.

Using Filters in Expressions

Filters can be used in expressions to format or transform data before displaying it in the view. For example, to format a date using the date filter:

<div ng-controller="myController">
    <p>Today's date: {{ currentDate | date: 'MM/dd/yyyy' }}</p>
</div>

In this example, the date filter is applied to the currentDate expression to format the date in the specified format.

Using Filters in Directives

Filters can also be used with directives that support filtering, such as the ng-repeat directive. Filters are applied to the data displayed by the directive:

<div ng-controller="myController">
    <ul>
        <li ng-repeat="item in items | filter: 'filterText'">{{ item.name }}</li>
    </ul>
</div>

In this example, the filter filter is applied to the items array to filter items based on the filterText value. Only items that match the filter text will be displayed.

Custom Filters

AngularJS allows you to create custom filters tailored to your application’s specific requirements. Custom filters are defined as JavaScript functions and are registered with the module using the filter method. Here’s how to create a custom filter that capitalizes the first letter of a string:

app.filter('capitalize', function() {
    return function(input) {
        if (input && typeof input === 'string') {
            return input.charAt(0).toUpperCase() + input.slice(1);
        }
        return input;
    };
});

In this example, the capitalize filter is defined, and it returns a function that takes an input and capitalizes the first letter. The filter is registered with the module, making it available for use in expressions and directives.

Using Custom Filters

Once a custom filter is defined and registered, you can use it in your application just like built-in filters. For example, to capitalize the first letter of a string:

<div ng-controller="myController">
    <p>{{ text | capitalize }}</p>
</div>

In this example, the capitalize filter is applied to the text expression, capitalizing the first letter of the string.

Custom filters provide a way to encapsulate common data transformations or formatting requirements and reuse them throughout your application.

Chaining Filters

AngularJS allows you to chain multiple filters together in an expression or directive. Chaining filters enables complex data transformations by applying a series of filters one after another. For example, you can chain the uppercase and limitTo filters to uppercase a string and limit its length:

<div ng-controller="myController">
    <p>{{ description | uppercase | limitTo: 20 }}</p>
</div>

In this example, the description expression is first passed through the uppercase filter to convert the text to uppercase and then through the limitTo filter to limit the string to the first 20 characters.

Chaining filters allows you to create versatile and expressive data transformations.

Filter Parameters

Filters can accept parameters to customize their behavior. Parameters are specified after a colon within the filter expression. For example, the limitTo filter accepts a parameter to specify the maximum number of characters to display:

<div ng-controller="myController">
    <p>{{ longText | limitTo: 50 }}</p>
</div>

In this example, the limitTo filter is given the parameter 50 to limit the longText expression to a maximum of 50 characters.

Different filters accept different parameters, and it’s essential to refer to AngularJS documentation to understand the parameters and options available for each filter.

Filtering Data with Expressions

Filters are commonly used in combination with directives like ng-repeat to filter and display data dynamically. For example, you can use the filter filter to search and filter items within a list:

<div ng-controller="myController">
    <input type="text" ng-model="filterText" placeholder="Search items">
    <ul>
        <li ng-repeat="item in items | filter: filterText">{{ item.name }}</li>
    </ul>
</div>

In this example, the filterText expression is used to filter items based on the search text entered in the input field.

Best Practices for Using Filters

When working with filters in AngularJS, consider the following best practices:

  1. Keep Filters Simple: Avoid complex logic or extensive computations within filters. Filters should primarily focus on formatting or transforming data.
  2. Use Custom Filters for Reusability: Create custom filters for common formatting or data transformation requirements to promote code reuse and maintainability.
  3. Mind Performance: Filters can impact the performance of your application, especially if they are applied to a large dataset. Be mindful of performance considerations and limit the number of filters used in performance-critical scenarios.
  4. Know the Available Filters: Familiarize yourself with the built-in filters provided by AngularJS and refer to the documentation for details on their usage.
  5. Test Custom Filters: When creating custom filters, ensure they are thoroughly tested to handle various input scenarios.

Conclusion

Filters in AngularJS provide a powerful way to format, transform, and filter data presented in your web applications. Built-in filters and custom filters can be applied to expressions and directives, enabling you to create dynamic and user-friendly interfaces. Understanding the capabilities and best practices for working with filters is essential for building effective and maintainable AngularJS applications.

In the next chapter, we will explore directives, a core feature of AngularJS that extends HTML with custom behavior and enhances the interactivity of your web applications.

Scroll to Top