SoFunction
Updated on 2025-04-11

Summary of usage of AngularJS filter filter

This article summarizes the usage of AngularJS filter filter. Share it for your reference, as follows:

introduction

Built-in filter

ng has some filters built in, which are: currency, date, filter (substring matching), json (formatting json objects), limitTo (limiting the number), lowercase (lowercase), uppercase (uppercase), number (number), orderBy (sorting). There are nine types in total. In addition, you can also customize filters, which is powerful and can meet any requirements for data processing. Let’s take a look at their usage;

1. currency (currency processing)

Use currency to format numbers as currency, the default is the dollar sign, you can pass in the required symbol yourself, for example, I pass in RMB:

{{num | currency : '¥'}}

2. date (date formatting)

The native js has limited formatting capabilities for dates, and the date filter provided by ng can basically meet general formatting requirements. The usage is as follows:

{{date | date : 'yyyy-MM-dd hh:mm:ss EEEE'}}

Parameters are used to specify the desired format. y M d h m s E represents year, month, day, hour, minute, second, week, respectively, and you can freely combine them. Different numbers can also be used to limit the number of formatted bits. In addition, the parameters can also use specific descriptive strings, such as "shortTime" that will format the time as 12:05 pm. ng provides eight descriptive strings. I personally think these are a bit redundant. I can combine the desired format according to my own wishes and don’t want to memorize so many words~

3. filter (match substring)

This filter (I have to say that this name is really confusing -!) is used to process an array, and then the elements containing a certain substring can be filtered out and returned as a subarray. It can be an array of strings or an array of objects. If it is an array of objects, the value of the attribute can be matched. It receives a parameter that defines the matching rules for the substring. Here is an example to illustrate the usage of parameters. I used several children who are particularly popular to define an array:

$ = [
    {name:'kimi',age:3},
    {name:'cindy',age:4},
    {name:'anglar',age:4},
    {name:'shitou',age:6},
    {name:'tiantian',age:5}
  ];
$ = function(e){return >4;}
{{ childrenArray | filter : 'a' }} //The matching attribute value contains a{{ childrenArray | filter : 4 }} //The matching attribute value contains 4{{ childrenArray | filter : {name : 'i'} }} //The parameter is an object, matching the name attribute containing i{{childrenArray | filter : func }} //The parameter is a function, specifying that the return age>4 is

4. json (formatting json object)

The json filter can format a js object into a json string without parameters. What's the use of this thing? I usually don't output a json string on the page. The official website says it can be used for debugging. Well, it's a good choice. Alternatively, it can also be used in js, and its function is the same as we are familiar with (). Super simple usage:

{{ jsonTest | json}}

5. limitTo (limit the array length or string length)

The limitTo filter is used to intercept an array or string, and receives a parameter to specify the length of the intercept. If the parameter is a negative value, it starts from the end of the array. I personally think this filter is a bit useless. First of all, it can only be intercepted from the beginning/end of an array or string. Secondly, js native functions can replace it. Let's see how to use it:

{{ childrenArray | limitTo : 2 }} //The first two items in the array will be displayed

6. lowercase (lowercase)

Convert data to all lowercase. Too simple, I won't explain much. It is also a very useless filter. It has no parameters and can only turn the entire string into lowercase and cannot specify letters. I'm too lazy to write it no matter how I use it.

7. uppercase (caps)

Same as above.

8. number (formatted numbers)

The number filter can be split to a number with thousands, like this, 123,456,789. Receive a parameter at the same time, and you can specify how many decimal places to retain:

{{ num | number : 2 }}

9. orderBy(sort)

The orderBy filter can sort elements in an array and receive a parameter to specify the sorting rules. The parameter can be a string that indicates sorting by the attribute name. It can be a function that defines sorting properties. It can also be an array that means sorting by the attribute values ​​in the array in turn (if the values ​​compared by the first item are equal, then compare by the second item), or take the above child array as an example:

<div>{{ childrenArray | orderBy : 'age' }}</div>   //Sort by age attribute value. If it is -age, the order will be reversed.<div>{{ childrenArray | orderBy : orderFunc }}</div>  //Sort by the return value of the function<div>{{ childrenArray | orderBy : ['age','name'] }}</div> //If the age is the same, sort by name

The built-in filter has been introduced, and I am almost asleep when I write it. . . As you can see, the built-in filters in ng are not omnipotent, and in fact many of them are a bit useless. More personalized needs require us to define our own filters.

Custom filters

We need to use the filter in the module to define a function. This function receives the input value and then returns the result we want after a series of processing. For example, in the following example, we realize the return value with an odd subscript in the array.

('odditems',function(){
  return function(inputArray){
    var array = [];
    for(var i=0;i<;i++){
      if(i%2!==0){
        (inputArray[i]);
      }
    }
    return array;
  }
});

This is the format, and your processing logic is written in the internal closure function. You can also let your filter receive parameters, and the parameters are defined in the return function, as the second parameter, or more parameters.

Two usages of filters

1. Use filter in templates

We can use filter directly in {{}}, followed by the expression and split it with |. The syntax is as follows:

{{ expression | filter }}

You can also use multiple filters in conjunction, and the output of the previous filter will be used as the input of the next filter (no wonder this product is the same as the pipeline.)

{{ expression | filter1 | filter2 | ... }}

Filter can receive parameters, and the parameters are divided by: as follows:

{{ expression | filter:argument1:argument2:... }}

In addition to formatting the data in {{}}, we can also use filters in directives, such as filtering the array array first, and then

Loop output:

<span ng-repeat="a in array | filter ">

2. Use filter in controller and service

We can also use filters in our js code, which is the dependency injection we are familiar with. For example, if I want to use a currency filter in a controller, just inject it into the controller. The code is as follows:

('testC',function($scope,currencyFilter){
  $ = currencyFilter(123534);
}

Use {{num}} in the template to output $123,534.00 directly! The same is true for using filter in services.

At this time, you may have doubts. If I want to use multiple filters in the controller, would it take to inject one by one? Wouldn't it be too difficult? Don't worry, little brother~ng provides a $filter service to call the required filter. You only need to inject a $filter. The usage method is as follows:

('testC',function($scope,$filter){
  $ = $filter('currency')(123534);
  $ = $filter('date')(new Date(),"yyyy-MM-dd hh:mm:ss EEEE");
}

The same effect can be achieved. The advantage is that you can easily use different filters.

summary

For more information about AngularJS, readers who are interested in view the topic of this site:AngularJS Introduction and Advanced Tutorial"and"AngularJS MVC architecture summary

I hope this article will be helpful to everyone's AngularJS programming.