English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed Explanation of AngularJS Filters (Built-in and Custom)

Filters are used to format the data that needs to be displayed to the user. AngularJS has many practical built-in filters, and it also provides
It provides a convenient way to create your own filters.

Use the | symbol to call filters within the template binding symbols {{ }} in HTML. For example: {{value|lowercase}}//Convert the value to lowercase

in JavaScript code, you can call filters through $filter}}

Example:

 app.controller(‘DemoController‘, [‘$scope‘, ‘$filter‘,
  function($scope, $filter) {
  $scope.name = $filter(‘lowercase‘)(‘Ruby‘);
  });

When using filters in HTML, if you need to pass parameters to the filter, just add a colon after the filter name
that's it. If there are multiple parameters, you can add a colon after each parameter.

For example

  {{0.23145|number:3}}

Display value: 0.231//Number filter can limit the number of decimal places after the decimal point (write2, to2to pass parameters to the filter)

You can use the | symbol as a delimiter to use multiple filters at the same time

One: Below is an introduction to the built-in filters provided by AngularJS:

 1.currency filter can format a number into currency format. Use {{ 50| currency }} to convert50 to currency format.
The currency filter allows us to set the currency symbol ourselves. By default, it will use the currency symbol of the client's region,
but you can also customize the currency symbol.

2.date filter can format the date into the desired format. AngularJS has several built-in date formats, if not

Specify any format, the default will be mediumDate format

Below are the built-in localized date formats supported:

{{ today | date:‘medium‘ }} <!-- Aug 09, 2013 12:09:02 PM -->
{{ today | date:‘short‘ }} <!-- 8/9/1312:09PM -->
{{ today | date:‘fullDate‘ }} <!-- Thursday, August 09, 2013 -->
{{ today | date:‘longDate‘ }} <!-- August 09, 2013 -->
{{ today | date:‘mediumDate‘ }}<!-- Aug 09, 2013 -->
{{ today | date:‘shortDate‘ }} <!-- 8/9/13 -->
{{ today | date:‘mediumTime‘ }}<!-- 12:09:02 PM -->
{{ today | date:‘shortTime‘ }} <!-- 12:09 PM -->

 Year formatting

Four-digit year: {{ today | date:‘yyyy‘ }} <!-- 2013 -->
Two-digit year: {{ today | date:‘yy‘ }} <!-- 13 -->
One-digit year: {{ today | date:‘y‘ }} <!-- 2013 -->

Month formatting

English month: {{ today | date:‘MMMM‘ }} <!-- August -->
English abbreviation of the month: {{ today | date:‘MMM‘ }} <!-- Aug -->
Numeric month: {{ today |date:‘MM‘ }} <!-- 08 -->
Month of the year: {{ today |date:‘M‘ }} <!-- 8 -->

Date formatting

Numeric date: {{ today|date:‘dd‘ }} <!-- 09 -->

Day of the month in a month: {{ today | date:‘d‘ }} <!-- 9 -->

English day of the week: {{ today | date:‘EEEE‘ }} <!-- Thursday -->
English abbreviation of the day of the week: {{ today | date:‘EEE‘ }} <!-- Thu -->

Hour formatting

2412-hour format numeric hour: {{today|date:‘HH‘}} <!--00-->
Hour within a day: {{today|date:‘H‘}} <!--0-->
1212-hour format numeric hour: {{today|date:‘hh‘}} <!--12-->
Hour within AM/PM: {{today|date:‘h‘}} <!--12-->

Minute formatting

Numeric minute: {{ today | date:‘mm‘ }} <!-- 09 -->
Minute within an hour: {{ today | date:‘m‘ }} <!-- 9 -->

Second formatting

Numeric second: {{ today | date:‘ss‘ }} <!-- 02 -->
Second within a minute: {{ today | date:‘s‘ }} <!-- 2 -->
Milliseconds: {{ today | date:‘.sss‘ }} <!-- .995 -->

Character formatting

AM/PM indicator: {{ today | date:‘a‘ }} <!-- AM -->
Four-digit timezone identifier: {{ today | date:‘Z‘ }} <!--- 0700 -->

Custom date format example:

{{ today | date:‘MMMd, y‘ }} <!-- Aug9, 2013 -->
{{ today | date:‘EEEE, d, M‘ }} <!-- Thursday, 9, 8-->
{{ today | date:‘hh:mm:ss.sss‘ }} <!-- 12:09:02.995 -->

3.filter

  The filter function can select a subset from the given array and return a new array. This filter is usually used to filter elements that need to be displayed.

  The first parameter of this filter can be a string, an object, or a function used to select elements from an array.

 1)The parameter is a string when passed in}}

    It returns all elements that contain this string. If we want to return elements that do not contain the string, add the ! symbol before the parameter.

   Example:

      {{ [‘Bri‘,‘Lerner‘,‘Likes‘,‘To‘,‘Eat‘,‘Pizza‘] | filter:‘e‘ }}

  <!-- ["Lerner","Likes","Eat"] -->

2)The parameter passed in is an object

   AngularJS will compare the properties of the object to be filtered with the same-named properties in this object. If the property value is a string, it will be judged whether it contains the string. If we want to compare all properties, we can use $ as the key name.

Example:

 {{ [{
      'name': 'Ari',
      ‘City‘: ‘San Francisco‘,
      ‘favorite food‘: ‘Pizza‘
    },{
      'name': 'Nate',
      ‘City‘: ‘San Francisco‘,
      ‘favorite food‘: ‘indian food‘
  }] | filter:{‘favorite food‘: ‘Pizza‘} }}
<!-- [{"name":"Ari","City":"SanFrancisco","favoritefood":"Pizza"}] -->

3)function

   This function is executed for each element, and the elements that return non-false values will appear in the new array and be returned.

  Custom functions can be used for filtering (in this example, the function is defined on $scope):

{{ [‘Ari‘,‘likes‘,‘to‘,‘travel‘] | filter:isCapitalized }}
 <!-- ["Ari"] -->
 The function of 'isCapitalized' is to return true or false based on whether the first letter is capitalized, as shown below:
 $scope.isCapitalized = function(str) {
 return str[0] == str[0].toUpperCase();
 };

4.json

The 'json' filter can convert a JSON or JavaScript object into a string. This conversion is very helpful for debugging:
  {{ {‘name‘: ‘Ari‘, ‘City‘: ‘SanFrancisco‘} | json }}
  <!--
    {
      "name": "Ari",
      "City": "San Francisco"
    }
  -->

5.limitTo

 The 'limitTo' filter generates a new array or string based on the parameters passed, with the length of the new array or string depending on the parameters. It controls whether to start cutting from the front or the back by passing the positive or negative value of the parameters. (If the length value passed in is greater than the length of the array or string being operated on, the entire array or string will be returned.)

Example: }}

 {{ San Francisco is very cloudy | limitTo:3 }}
 <!-- San -->
 {{ San Francisco is very cloudy | limitTo:-6 }}
 <!-- cloudy -->

 The same operation can also be performed on arrays. Return the first element of the array:

  {{ [‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘] | limitTo:1 }}
  <!-- ["a"] -->

6 lowercase

  The lowercase filter converts a string to lowercase.

7.number

  The number filter formats numbers into text. The second parameter is optional and is used to control the number of decimal places to be truncated. (If a non-numeric character is passed in, an empty string will be returned.)

8.orderBy

  orderBy filter can sort the specified array with an expression.

  orderBy can accept two parameters, the first is required, and the second is optional.

  The first parameter is used to determine the predicate for the array sorting direction.

 The following discusses the type of the first parameter in different cases.

   function
  When the first parameter is a function, the function is used as the getter method of the object to be sorted.

   string
  The parsing result of this string will determine the sorting direction of the array elements. We can pass+or-to force ascending or descending order.

   Array
  Use array elements as predicates in the sorting expression. For each element that does not strictly match the expression result, use the first predicate.

 The second parameter is used to control the direction of sorting (whether reverse).

  Example:

 {{ [{
    'name': 'Ari',
    'status': 'awake'
   },{
    'name': 'Q',
    'status': 'sleeping'
  },{
    'name': 'Nate',
    'status': 'awake'
  }] | orderBy: 'name' }}
  <!--
    [
    {"name":"Ari","status":"awake"},
    {"name":"Nate","status":"awake"},
    {"name":"Q","status":"sleeping"}
    ]  
  -->

 Reverse the sorting results (by setting the second parameter to true, the sorting results can be reversed: orderBy: 'name': true)

9.uppercase

 The uppercase filter can convert a string to uppercase form:

 Second: Custom Filter

 To create a custom filter, it needs to be placed in its own module.

Here is an example to illustrate:

 Display the name in uppercase format

<!DOCTYPE html>
<html>
<head>
 <title>Custom Filter</title>
 <meta charset="utf-8" />
 <script type="text/javascript" src="angular.min.js"></script>
</head>
<body ng-app="customFilter" ng-controller="filterController">
 <h1>{{name|lowercase|Capitalize}}<//h1>
 <script type="text/javascript" src="customfilter.js"></script>
</body>
</html>

customfilter.js

(function () {
 var app = angular.module('customFilter', []);
 app.controller('filterController', function ($scope) {
  $scope.name = 'JACK';
 });
 app.filter('Capitalize', function () {
  return function (input) {
   if (input) {
    return input[0].toUpperCase() + input.slice(1);
   }
  };
 });
});

This is the material collection of AngularJS filters. We will continue to supplement relevant materials in the future, thank you all for your support to this site!

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like