Full parsing of filter usage in AngularJS

Source: Internet
Author: User
This article mainly introduces the use of filter in AngularJS, including listing some commonly used built-in filters in Angular and the methods for customizing filters, for more information, see the world of AngularJS. filter provides a method to format data. Angular also provides many built-in filters, in addition, it is quite simple to create a custom filter.

In the HTML template binding {}, we use | to call the filter. For example, we want to display all uppercase characters of the string:

{{ name | uppercase }}

Of course, we can also use the $ filter service in JavaScript to call the filter, and use uppercase strings for example:

app.controller('DemoController', ['$scope', '$filter', function($scope, $filter) {    $scope.name = $filter('lowercase')('Ari');}]);

How do I pass parameters to the filter? You only need to put the parameter after the filter, and add a colon in the middle (if there are multiple parameters to be passed, add a colon after each parameter). For example, the digital filter can help us limit the number of digits, if you want to display two decimal places, add number: 2.

{{ 123.456789 | number:2 }}

The filter is mainly used to filter an array and return a new array containing sub-array data.

For example, when searching on the client, we can quickly filter out the desired results from the array.

This filter method receives a string, object, or function parameter to select/remove array elements.

For details, refer:

1. built-in filters
1, uppercase, lowercase size conversion

{"Lower cap string" | uppercase} // result: lower cap string {"TANK is GOOD" | lowercase} // result: tank is good

| The vertical line here is a type of Pipeline Function. If you are familiar with linux, this line | the Pipeline Function of the root linux is basically the same 2, json format

{Foo: "bar", baz: 23} | json} // result: {"foo": "bar", "baz": 23}

Note: bza is not formatted with double quotation marks. After formatting, it is converted into json data.

3, date Format

Mysql timestamp ng-bind = "message. time * 1000 | date: 'yyyy-mm-dd '"

{1304375948024 | date: 'medium '}}// May 03,201 1 06:39:08 PM {1304375948024 | date }}// result: May 3, 2011 {1304375948024 | date: "MM/dd/yyyy @ h: mma" }}// result: 05/03/2011 @ 6:39 AM {1304375948024 | date: "yyyy-MM-dd hh: mm: ss "}}// result: 06:39:08

4. number formatting

{1.234567 | number: 1 }}// result: 1.2 {1234567 | number} // result: 1,234,567

5. Format currency

{250 | currency }}// result: $250.00 {250 | currency: "RMB ¥" }}// result: RMB ¥250.00

6. The filter can only query values, but cannot query keys.

{[{"Age": 20, "id": 10, "name": "iphone" },{ "age": 12, "id": 11, "name": "sunm xing" },{ "age": 44, "id": 12, "name": "test abc"}] | filter: 'S '} // find the row containing s // result of the preceding example: [{"age": 12, "id": 11, "name ": "sunm xing" },{ "age": 44, "id": 12, "name": "test abc"}] {[{"age": 20, "id": 10, "name": "iphone" },{ "age": 12, "id": 11, "name": "sunm xing "}, {"age": 44, "id": 12, "name": "test abc"}] | filter: {'name ': 'IP' }}// find the row of name like ip // the preceding example result: [{"age": 20, "id": 10, "name ": & quot; iphone & quot;}] $ filter ('number') (30000, 2); var jsonString = $ filter ('json') ({& quot; age & quot;: 12, & quot; id & quot ": 11, "name": "sunm xing" },{ "age": 44, "id": 12, "name": "test abc"}])

7, limitTo string, screenshot of the image

{"I love tank" | limitTo: 6} // result: I love {"I love tank" | limitTo:-4} // result: tank {[{"age": 20, "id": 10, "name": "iphone" },{ "age": 12, "id": 11, "name": "sunm xing" },{ "age": 44, "id": 12, "name": "test abc"}] | limitTo: 1 }}// result: [{"age": 20, "id": 10, "name": "iphone"}]

8. Order

{[{"Age": 20, "id": 10, "name": "iphone" },{ "age": 12, "id": 11, "name": "sunm xing" },{ "age": 44, "id": 12, "name": "test abc"}] | orderBy: 'id ': true }}// sort the root id in descending order {[{"age": 20, "id": 10, "name": "iphone" },{ "age ": 12, "id": 11, "name": "sunm xing" },{ "age": 44, "id": 12, "name ": "test abc"}] | orderBy: 'id'} // sort by id in ascending order {[{"age": 20, "id": 10, "name": "iphone" },{ "age": 12, "id": 11, "name": "sunm xing" },{ "age": 44, "id": 12, "name": "test abc"}] | orderBy: ['-age', 'name']}

Ii. Custom filter Function
The custom filter method is also very simple. The module filter method is used to return a function that receives input values and returns the processed results.

App. filter ('filter name', function () {return function (object to be filtered, filter parameter 1, filter parameter 2 ,...) {//... objects after return processing ;}});

I found a mvc Framework of angularjs, phonecat, and custom filter, which is also written on this basis. This framework is quite useful.
Add a module in filters. js.

angular.module('tanktest', []).filter('tankreplace', function() {  return function(input) {    return input.replace(/tank/, "=====")  };});

Call in html

{"TANK is GOOD" | lowercase | tankreplace} // result: ==== is good

Note: | lowercase | the tankreplace pipeline command can have multiple

yourApp.filter('orderObjectBy', function() { return function(items, field, reverse) {  var filtered = [];  angular.forEach(items, function(item) {   filtered.push(item);  });  filtered.sort(function (a, b) {   return (a[field] > b[field] ? 1 : -1);  });  if(reverse) filtered.reverse();  return filtered; };});

This filter converts an object to a standard array and sorts it by the specified field. You can use the orderObjectBy filter to look like ORDERBY, including a Boolean value after the field name, to determine whether to be reversed in the specified order. In other words, what is false is ascending and actually falling. Html call

  • {{ item.color }}
  • Sort search

          
         Product NO.    Product Name    Product Price        {Item. id }}    {Item. name }}    {Item. price | currency: '¥ '}}  

    Angularjs

    // Default sorting field $ scope. orderType = 'id'; $ scope. order = '-'; $ scope. changeOrder = function (type) {console. log (type); $ scope. orderType = type; if ($ scope. order = '') {$ scope. order = '-';} else {$ scope. order = '';}}

    For more information about completely parsing filter usage in AngularJS, refer to PHP!

    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.