Summary of the use of filter filter Angularjs _ANGULARJS

Source: Internet
Author: User
Tags array length json lowercase

The example of this article summarizes the usage of filter filter angularjs. Share to everyone for your reference, specific as follows:

Introduction

Filter filters for us is not unfamiliar, he and our real life filter meaning is similar, its role is to receive a input value, and then follow a rule to process and then output the final result, such as we enter a number, and then we need to get the currency form of data, So we can use the filter to achieve, ANGULARJS filter is very simple, divided into built-in and custom two kinds, the following small series is simple to introduce some.

Built-in filters

NG has built-in filters that are: currency (currency), date (date), filter (substring match), JSON (formatted JSON object), LimitTo (limit), lowercase (lowercase), uppercase (uppercase), Number (numbers), by order (sort). Total nine species. In addition, you can customize the filter, this is powerful, can meet any requirements of data processing. Let's take a look at how they are used;

1. Currency (currency processing)

Using currency, you can format numbers as currency, by default a dollar sign, and you can pass in the required symbols yourself, such as my incoming RMB:

{{num | currency: ' ¥ '}}

2. Date (dated format)

Native JS has a limited ability to format dates, and the date filters provided by Ng can basically meet the general formatting requirements. Usage is as follows:

{date |: ' Yyyy-mm-dd hh:mm:ss eeee '}}

The parameters are used to specify the desired format, and y m D H s E represents the time of the month and the week, and you are free to combine them. You can also use different numbers to limit the number of digits that are formatted. Additional parameters can also use a specific descriptive string, such as "Shorttime", which will format the time as 12:05 pm. NG provides eight kinds of descriptive strings, personally feel that these are a little superfluous, I can completely according to their own will combine the desired format, do not want to remember so many words ~

3. Filter (matching substring)

The filter called filter (which has to be said to be the name, it is easy to confuse--! is used to process an array, and then it can filter out elements that contain a substring and return it as a child array. Can be either 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 rule for the substring. Here's an example of how the parameters are used, and I've defined an array with some of the kids that 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 {{
Childrenarray | filter:4}}///matching attribute value containing 4
{{Childrenarray | Filter: {name: ' I '}}///parameter is an object that matches the
{{Childrenarray | filter:func}}//parameter that contains I in the Name property, which specifies a function that returns the AGE>4

4. JSON (format JSON object)

The JSON filter can format a JS object as a JSON string with no parameters. What is the use of this thing, I generally will not output a JSON string on the page ah, the official website said it can be used for debugging, well, is a good choice. Or, it can be used in JS, the role of the same as we are familiar with the json.stringify (). Usage Super simple:

{{jsontest | json}}

5. LimitTo (Limit array length or string length)

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

{{Childrenarray | limitto:2}}//will display the first two items in the array

6. Lowercase (lowercase)

Converts the data to all lowercase. It's too easy, not much to explain. Also is very chicken a filter, without parameters, only the entire string into lowercase, can not specify the letter. I'm too lazy to write anything.

7. Uppercase (capital)

Ditto.

8. Number (formatted)

Number filters can add thousands to a digit, like this, 123,456,789. Receives a parameter at the same time, you can specify that float type retains several decimal places:

{{num | number:2}}

9. By order (sort)

The order by filter can sort the elements in an array, receive a parameter to specify the collation, and the parameter can be a string representing the sort by the property name. Can be a function that defines the sort attribute. It can also be an array that is sorted by the values of the properties in the array (if the values are compared by the first item, and then by the second), or by taking an example of the children above:

<div>{{Childrenarray | By: ' Age '}}</div>   //sorted by age attribute value, if-age, then reverse
<div>{{ Childrenarray | Orderby:orderfunc}}</div>  //sorted by function return value
<div>{{Childrenarray | by: [' age ', ' name ']}}< /div>//If Age is the same, sort by name

The built-in filter is finished, and I'm almost asleep. As you can see, NG built-in filter is not omnipotent, in fact, a lot of relatively chicken. More personalized requirements will require us to define our own filters.

Custom Filters

We need to define a function by using the filter in module, which receives the input value and then returns the desired result through a series of processing, such as the following example, which returns an odd number of values in the lower and middle of the array.

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 filters receive parameters, which are defined in the return function, as the second argument, or more arguments.

Two ways to use a filter

1. Using filter in the template

We can use filter directly in {{}}, following the expression with | Split, the syntax is as follows:

{{expression | filter}}

can also be used with multiple filter, the output of the last filter will be the input of the next filter (no wonder the cargo is the same as the pipe.) )

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

Filter can receive parameters by: Split, as follows:

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

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

Loop output:

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

2. Use of filter in controller and service

Our JS code can also use filters, the way we are familiar with dependency injection, such as 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);
}

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

At this point you may have doubts, if I want to use multiple filter in the controller, is it not too strenuous to have an injection? Don't worry, little brother. ~ng provides a $filter service to invoke the desired filter, you just 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 (), "Yyyy-mm-dd hh:mm:ss eeee");
}

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

Summary

The above is about the filter in the Angularjs of some basic usage, are very simple, small knitting in this will impress some, filter study no difficult place, then we can directly query the relevant documents on it.

More readers interested in ANGULARJS related content can view the site topics: "Angularjs Introduction and Advanced Tutorials" and "ANGULARJS MVC Framework Summary"

I hope this article will help you to Angularjs program design.

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: 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.