Angular's filter study

Source: Internet
Author: User

Filters (filter), as its name, is to receive an input, process it through a rule, and return the processed results. It is used primarily for formatting data, such as getting a subset of an array, sorting the elements in a group, and so on. Ng contains filters that are: currency (currency), date (date), filter (substring match), JSON (formatted JSON object), LimitTo (number of limits), lowercase (lowercase), uppercase (uppercase), Number (numbers), order by (sort). Total nine kinds. In addition to the custom filter, this is powerful enough to meet any required data processing.

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

Two ways to use filter 1. Using the filter in a template

We can use filter directly in {{}}, followed by an expression | The syntax for partitioning is as follows:

{{expression | filter}}

You can also use multiple filter, and the output of the previous filter will be the input of the next filter (no wonder the cargo is a pipe-like type.) )

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

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

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

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

<span ng-repeat= "A in array | Filter ">

2. Using the filter in controller and service

We can also use filters in our JS code, the way we are familiar with dependency injection, for example, I want to use the currency filter in the controller, just inject it into the controller, the code is as follows:

App.controller (' TESTC ', function ($scope, currencyfilter) {    $scope. num = Currencyfilter (123534);  }

Using {{num}} in the template can output $123,534.00 directly! Using filter in a service is the same thing.

You may have doubts at this point, if I want to use more than one filter in the controller, is it too much to inject one? Little Brother Mo Anxious ~ng provides a $filter service to invoke the desired filter, you only need to inject a $filter is enough, use the following method:

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.

Ng's built-in filter

Ng has built-in nine filters, which are easy to use and read in the documentation. However, in order not to go through its documentation, I will make a detailed record here.

1. Currency (currency processing)

Using currency, you can format numbers as currency, which is the dollar sign by default, and you can pass in the required symbols yourself, such as when I pass in renminbi:

{{num | currency: ' ¥ '}}
2. Date (dates formatted)

Native JS has limited formatting capabilities for dates, and the date filter provided by Ng basically meets the general formatting requirements. Use the following:

{{date | date: ' YYYY-MM-DD hh:mm:ss eeee '}}

The parameters are used to specify the desired format, and y m D H m S E respectively represent the day of the month and the week, and you are free to combine them. You can also use different numbers to limit the number of formatted digits. Other parameters can also use a specific descriptive string, such as "Shorttime" will format the time as 12:05 pm. NG provides eight descriptive strings that I think are a bit superfluous, and I can combine the desired format with my own will, and I don't want to remember so many words ~

3. Filter (matched substring)

This filter, which is called filter (which has to be called, is easy to confuse--! ) is used to process an array and can then filter out elements containing a substring to be returned as a subarray. Can be an array of strings, or an array of objects. If it is an array of objects, you can match the value of the property. It receives a parameter that defines the matching rules for the substring. Here's an example of how the parameters are used, and I've defined an array with a few kids who are now particularly hot:

$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 '}}//Match attribute value contains a in {{Childrenarray | filter:4}}  //Match attribute value contains 4 {{Childrenarray | filter : {name: ' I '}}}//parameter is an object that matches the {{Childrenarray | filter:func}}//parameter that contains I in the name attribute  is a function that specifies the return age>4 of the
4. JSON (format JSON object)

The JSON filter can format a JS object as a JSON string with no parameters. What's the use of this thing, I generally do not output a JSON string on the page ah, the official website said it can be used for debugging, well, is a good choice. Alternatively, it can be used in JS as well as the familiar json.stringify (). The usage is super simple:

{{jsontest | json}}
5. LimitTo (Limit array length or string length)

The LimitTo filter is used to intercept an array or string, receive a parameter to specify the length of the intercept, or, if the argument is negative, to intercept from the end of the array. Personally think this filter is a little chicken, first only from the beginning/end of the array or string interception, second, JS primitive function can replace it, see how to use it:

{{Childrenarray | limitto:2}}  The first two items in the array are displayed
6. Lowercase (lowercase)

Convert the data to all lowercase. It's too simple, not much to explain. The same is a very chicken filter, no parameters, only the entire string into lowercase, cannot specify the letter. I'm too lazy to write anything.

7. Uppercase (UPPERCASE)

Ditto.

8. Number (formatted numbers)

The number filter can be divided into thousands, like this, 123,456,789. Also receives a parameter, you can specify the float type to retain several decimals:

{{num | number:2}}
9. Order BY (sort)

Order BY filter You can sort the elements in an array, receive a parameter to specify the collation, and the argument can be a string representing the sort by the property name. Can be a function that defines a sort property. It can also be an array that is sorted by the property values in the array (if the value is equal by the first item, then the second one), or by an example of the child array above:

<div>{{Childrenarray | Order: ' age '}}</div>      //Sort by age attribute value, if-age, reverse <div>{{Childrenarray | Orderby:orderfunc}}</div>   //Sort by the return value of the function <div>{{Childrenarray | order: [' age ', ' name ']}}</div& gt;  If age is the same, sort by name

The built-in filters are finished, and I'm almost asleep ... As you can see, Ng built-in filters are not all-purpose, in fact, a lot of more chicken. The more personalized requirements we need to define our own filters, let's look at how to customize the filter.

Custom Filters

The custom method of filter is also simple, using the module's filter method, returns a function that receives the input value and returns the processed result. Words don't say much, let's write a look. For example, I need a filter that returns an array of elements that are labeled as odd, with the following code:

App.filter (' Odditems ', function () {    return function (inputarray) {        var array = [];        for (Var i=0;i<inputarray.length;i++) {            if (i%2!==0) {                array.push (inputarray[i]);            }        }        return array;    }});

The format is this, and your processing logic is written in the inner closure function. You can also have your filter receive parameters, the parameters are defined in the return function, as the second parameter, or more parameters can also.

Note: The first parameter here accepts the value of the currently filtered expression, which is passed to the system by default. All if you want to pass parameters, you need to start with the second argument.

In addition a custom filter example is attached:

<body> <div ng-controller= "Testctl" > <div>{{Sex| Sexflt: ' Compatriots '}}        </div> </div> </body> <script type= "Text/javascript" >Angular.module (' App ', []). Filter (' Sexflt ',function(){          return function(val,append) {if(val = = 0 ){              return' Male ' +append; }Else{              return' Female ' +append; }}). controller (' Testctl ',function($scope) {$scope. Sex= 0; })     </script>

Angular's filter study

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: info-contact@alibabacloud.com 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.