AngularJS filter (self-built and self-built) details, angularjs self-built

Source: Internet
Author: User
Tags month name

AngularJS filter (self-built and self-built) details, angularjs self-built

The filter is used to format the data to be presented to the user. AngularJS has a lot of practical built-in filters
You can create a filter by yourself.

Use the | symbol to call the filter in the template binding symbol {} in HTML. Example: {value | lowercase} // convert the value to lowercase

You can use $ filter to call the filter in JavaScript code.


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

When using a filter in HTML format, if you need to pass parameters to the filter, you only need to add a colon after the Filter Name
You can. If multiple parameters exist, you can add a colon to each parameter.

For example

{0.23145 | number: 3 }}

Display value: 0.231 // a numerical filter can limit the number of digits after the decimal point (write 2 after the filter and pass 2 as a parameter to the filter)

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

I. the built-in filter provided by AngularJS is introduced below:

1. The currecy filter can format a value as a currency. Use {50 | currency} to convert 50 to the currency format.
The currecy filter allows us to set currency symbols by ourselves. By default, the currency symbol of the region where the client is located is used,
However, you can also customize currency symbols.

2. The date filter can format the date into the required format. AngularJS has several built-in date formats.

Specify any format. The mediumDate format is used by default.

The following is a built-in date format that supports Localization:

{Today | date: 'medium '} <! -- Aug 09,201 3 12:09:02 -->
{Today | date: 'short '}}<! -- 8/9/1312: 09 PM -->
{Today | date: 'fulldate'} <! -- Thursday, August 09,201 3 -->
{Today | date: 'longdate'} <! -- August 09,201 3 -->
{Today | date: 'mediumdate'} <! -- Aug 09,201 3 -->
{Today | date: 'latest date'} <! -- 8/9/13 -->
{Today | date: 'mediumtime' }}<! -- 12:09:02 -->
{Today | date: 'processing time'} <! -- 12: 09 PM -->

Year format

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

Month formatting

English month: {today | date: 'mmmm' }}<! -- August -->
Abbreviated month name: {today | date: 'mmm' }}<! -- Aug -->
Digit month: {today | date: 'mm' }}<! -- 08 -->
Months of the year: {today | date: 'M' }}<! -- 8 -->

Date formatting

Digit date: {today | date: 'dd' }}<! -- 09 -->

Day of the month: {today | date: 'D' }}<! -- 9 -->

English week: {today | date: 'eeeee' }}<! -- Thursday -->
Abbreviated weekly Abbreviation: {today | date: 'Eee '}}<! -- Thu -->

Hour format

24-hour numeric hour: {today | date: 'hh' }}<! -- 00 -->
The hour of the day: {today | date: 'H' }}<! -- 0 -->
12-hour numeric hour: {today | date: 'hh' }}<! -- 12 -->
Morning or afternoon hours: {today | date: 'H' }}<! -- 12 -->

Minute format

Number in minutes: {today | date: 'mm' }}<! -- 09 -->
Minutes in an hour: {today | date: 'M' }}<! -- 9 -->

Format in seconds

Number of seconds: {today | date: 'ss' }}<! -- 02 -->
The second in a minute: {today | date: 's' }}<! -- 2 -->
Millisecond count: {today | date: '. ss' }}<! --. 995 -->

Character formatting

Last afternoon logo: {today | date: 'A' }}<! -- AM -->
Four-digit Time Zone ID: {today | date: 'Z' }}<! --- 0700 -->

Example of custom date format:

{Today | date: 'mmmd, y' }}<! -- Aug9, 2013 -->
{Today | date: 'eeee, d, M' }}<! -- Thursday, 9, 8 -->
{Today | date: 'hh: mm: ss. ss' }}<! -- 12:09:02. 995 -->

3. filter

The filter can select a subset from a given array and generate a new array. This filter is usually used to filter the elements 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) when the input parameter is a string

Returns all elements that contain this string. If we want to return an element that does not contain this string, add it before the parameter! Symbol.


{['Bri', 'lerner ', 'likes', 'to', 'eat', 'pizza'] | filter: 'E '}}

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

2) The input parameter is an object.

AngularJS compares the attributes of the object to be filtered with those of the same name in the object. If the attribute value is a string, AngularJS determines whether the object contains the string. If we want to compare all the attributes, we can use $ as the key name.


 {{ [{      ‘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) Functions

Execute this function for each element. elements that return non-dummy values will appear in the new array and return.

User-Defined Functions (in this example, the function is defined on $ scope ):

{['Ari ', 'likes', 'to', 'travel'] | filter: isCapitalized }}<! -- ["Ari"] --> the isCapitalized function returns true or false based on whether the initial letter is capitalized, as shown in the following code: $ 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 input parameters. The length of the new array or string depends on the input parameters, pass in the positive and negative values of the parameter to control whether to intercept from the front or back. (If the input length value is greater than the length of the operated array or string, the entire array or string will be returned .)


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

You can also perform the same operation on arrays. Returns the first element of the array:

{['A', 'B', 'C', 'D', 'E', 'F'] | limitTo: 1 }}
<! -- ["A"] -->

6 lowercase

The lowercase filter converts the string to lowercase.

7. number

The number Filter formats the number into text. Its second parameter is optional, used to control the number of digits after the decimal point. (If a non-numeric character is input, a null string is returned .)

8. orderBy

The orderBy filter can use an expression to sort the specified array.

OrderBy can accept two parameters. The first parameter is required, and the second parameter is optional.

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

The following describes the type of the first parameter.

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

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

Use array elements as predicates in the SORT expression. Use the first predicate for each element that is not strictly equal to the expression result.

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


 {{ [{    ‘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 result (you can reverse the sorting result by setting the second parameter to true: orderBy: 'name': true)

9. uppercase

The uppercase filter converts strings to uppercase:

Ii. Custom Filters

To create a custom filter, you need to put it in your own module.

The following is an example:

Name in upper case

<!DOCTYPE html>

Customfilter. js

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

The above is to sort out the AngularJS filter information, and continue to add relevant information in the future. Thank you for your support for this site!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.