Detailed explanation of the filter (filter) entering AngularJs

  • 2021-07-21 07:22:10
  • OfStack

The filter (filter), as its name suggests, takes 1 input, processes it through a rule, and returns the processed result. Mainly used in data formatting, such as getting a subset of an array, sorting the elements in the array, etc. ng has built-in filters: currency (currency), date (date), filter (substring matching), json (formatted json object), limitTo (limited number), lowercase (lowercase), uppercase (uppercase), number (number), orderBy (sort). There are 9 kinds in total. In addition, you can customize filters, which is powerful and can meet any requirements of data processing.

The content of the filter is very simple, as long as you understand how to use the built-in, how to define an filter on OK ~ today's system of learning, the following is an introduction.

Two Uses of filter

1. Use filter in templates

We can use filter directly in {{}}, following the expression with a partition, with the following syntax:


{{ expression | filter }}

It can also be used with multiple filter. The output of the last filter will be used as the input of the next filter (no wonder this cargo is as long as the pipeline.)


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

filter can receive parameters, which are divided by:, as follows:


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

In addition to formatting the data in {{}}, we can also use filter in instructions, such as filtering the array array first and then recycling the output:


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

2. Use filter in controller and service

We can also use filters in our js code in the familiar way of dependency injection, for example, if I want to use the currency filter in controller, I just need to inject it into the controller, and the code is as follows:


app.controller('testC',function($scope,currencyFilter){
 $scope.num = currencyFilter(123534); 
}

Using {{num}} in the template, you can directly output $123,534.00! The same is true of using filter in services.

At this point, you may wonder, if I want to use multiple filter in controller, do I need to inject one by one? Wouldn't it be too laborious? 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:


app.controller('testC',function($scope,$filter){
 $scope.num = $filter('currency')(123534);
    $scope.date = $filter('date')(new Date()); 
}

Can achieve the same effect. The advantage is that you can easily use different filter.

Built-in filter for ng

ng has built-in 9 kinds of filters, which are very simple to use and can be understood by reading documents. However, in order not to turn over its documents in the future, I still make a detailed record here.

1. currency (currency processing)

Using currency, you can format a number into currency. The default is US dollar symbol. 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 ability for dates, and the date filter provided by ng can basically meet the 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 denotes year, month, day, hour, second and week. You can combine them freely. You can also use different numbers to limit the number of digits formatted. Additional parameters can also use specific descriptive strings, such as "shortTime" will be time formatted as 12:05 pm. ng provides 8 descriptive strings. Personally, I think these are a little redundant. I can combine the desired format according to my own wishes, and I am unwilling to remember so many words ~

3. filter (matching substring)

This filter named filter (I have to say that this name is really confusing-!) Used to process an array, and then you can filter out elements containing a substring and return them as a subarray. It can be an array of strings or an array of objects. If it is an array of objects, it can match the value of attributes. It takes 1 parameter, which is used to define the matching rules of substrings. Here is an example to illustrate the usage of parameters under 1. I defined an array with several children who are particularly hot now:


$scope.childrenArray = [
  {name:'kimi',age:3},
  {name:'cindy',age:4},
  {name:'anglar',age:4},
  {name:'shitou',age:6},
  {name:'tiantian',age:5}
 ];

$scope.func = function(e){return e.age>4;}

{{ childrenArray | filter : 'a' }} // The matching attribute value contains a Adj. 
{{ childrenArray | filter : 4 }} // The matching attribute value contains 4 Adj. 
{{ childrenArray | filter : {name : 'i'} }} // Parameter is an object, matching name Property contains the i Adj. 
{{childrenArray | filter : func }} // Parameter is a function that specifies the return of age>4 Adj. 

4. json (Formatting json Objects)

The json filter can format an js object as an json string with no parameters. What's the use of this thing? I will not output an json string on the page. Official website said it can be used for debugging. Well, it is a good choice. Or, it can also be used in js, just like the familiar JSON. stringify () 1. Usage is super simple:


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

5. limitTo (Limit array length or string length)

The limitTo filter is used to truncate arrays or strings, and takes 1 parameter to specify the length of the truncation. If the parameter is negative, the truncation starts at the end of the array. Personally, I think this filter is a bit chicken ribs. First, it can only be intercepted from the beginning/end of an array or string. Secondly, the native function of js can replace it. See how to use it:


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

6. lowercase (lowercase)

Convert the data to all lowercase. It's too simple to explain. The same is very chicken ribs of 1 filter, no parameters, can only turn the whole string into lowercase, can not specify letters. I'm too lazy to write any more.

7. uppercase (capitals)

Ibid.

8. number (Formatted Numbers)

The number filter can divide 1 digit with thousands, like this, 123,456,789. Receiving 1 parameter at the same time, you can specify how many decimal places are reserved for float type:


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

9. orderBy (Sort)

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


<div>{{ childrenArray | orderBy : 'age' }}</div>  // Press age Property values, if the -age , then reverse order 
<div>{{ childrenArray | orderBy : orderFunc }}</div> // Sort by the return value of the function 
<div>{{ childrenArray | orderBy : ['age','name'] }}</div> // If age Same, according to name Sort 

After the introduction of the built-in filter, I almost fell asleep. . . As you can see, ng's built-in filters are not omnipotent. In fact, many of them are chicken ribs. More personalized requirements require us to define our own filters. Let's take a look at how to customize filters.

Custom filter

The custom way of filter is also very simple, using filter method of module to return a function, which receives the input value and returns the processed result. Without saying much, let's write one. For example, I need a filter that can return an array of elements with odd subscripts. The code is as follows:


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

This is the format. Your processing logic is written in the closure function inside. You can also have your filters take arguments, which are defined in the return function, as the second argument, or more arguments.

That's all the basics of filters. Again, what needs to be learned needs the real test of the project. Then, before the project comes, lay a good foundation ~


Related articles: