Home Web Front-end JS Tutorial A brief analysis of AngularJS Filter usage_AngularJS

A brief analysis of AngularJS Filter usage_AngularJS

May 16, 2016 pm 03:23 PM

I studied angularjs systematically and found that some ideas of angularjs are very similar to the PHP module smarty, such as data binding and filter. If you are familiar with smarty, it will be easier to learn angularjs. This article will introduce you to the detailed usage of angularjs filter. Friends who are interested can learn together

Filter Introduction

Filter is used to format data.

Basic prototype of Filter (‘|’ is similar to pipe mode in Linux):

Copy code The code is as follows:

{{ expression | filter }}

Filter can be used in a chain (that is, multiple filters are used continuously):

Copy code The code is as follows:

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

Filter can also specify multiple parameters:

Copy code The code is as follows:

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

AngularJS built-in Filter

AngularJS has built-in some commonly used Filters, let’s take a look at them one by one.

currencyFilter(currency):

Purpose: Format currency

Method prototype:

Copy code The code is as follows:

function(amount, currencySymbol, fractionSize)

Usage:

{{ | currency}}
{{ . | currency:'¥'}}
{{ . | currency:'CHY¥':}}
{{ . | currency:undefined:0}}

dateFilter(date):

Purpose: format date

Method prototype:

Copy code The code is as follows:

function(date, format, timezone)

Usage:


{{ '2015-05-20T03:56:16.887Z' | date:"MM/dd/yyyy @ h:mma"}}

{{ 1432075948123 | date:"MM/dd/yyyy @ h:mma"}}

{{ 1432075948123 | date:"MM/dd/yyyy @ h:mma":"UTC"}}

filterFilter(filter):

Purpose: filter array

Method prototype:

Copy code The code is as follows:

function(array, expression, comparator)

Usage 1 (use String for parameter expression):

 <div ng-init="myArr = [{name:'Tom', age:}, {name:'Tom Senior', age:}, {name:'May', age:}, {name:'Jack', age:}, {name:'Alice', age:}]">
   <!-- 参数expression使用String,将全文搜索关键字 'a' -->
   <div ng-repeat="u in myArr | filter:'a' ">
     <p>Name:{{u.name}}</p>
     <p>Age:{{u.age}}</p>
     <br />
   </div>
 </div>
Copy after login

Usage 2 (parameter expression uses function):

 // 先在Controller中定义function: myFilter
 $scope.myFilter = function (item) {
   return item.age === ;
 };
 <div ng-repeat="u in myArr | filter:myFilter ">
   <p>Name:{{u.name}}</p>
   <p>Age:{{u.age}}</p>
   <br />
 </div>
Copy after login

Usage 3 (use object for parameter expression):

 <div ng-init="myArr = [{name:'Tom', age:}, {name:'Tom Senior', age:}, {name:'May', age:}, {name:'Jack', age:}, {name:'Alice', age:}]">
   <div ng-repeat="u in myArr | filter:{age: } ">
     <p>Name:{{u.name}}</p>
     <p>Age:{{u.age}}</p>
     <br />
   </div>
 </div>
Copy after login

Usage 4 (specify comparator as true or false):

 <div ng-init="myArr = [{name:'Tom', age:}, {name:'Tom Senior', age:}, {name:'May', age:}, {name:'Jack', age:}, {name:'Alice', age:}]">
   Name:<input ng-model="yourName" />
   <!-- 指定comparator为false或者undefined,即为默认值可不传,将以大小写不敏感的方式匹配任意内容 -->
   <!-- 可以试试把下面代码的comparator为true,true即大小写及内容均需完全匹配 -->
   <div ng-repeat="u in myArr | filter:{name:yourName}:false ">
     <p>Name:{{u.name}}</p>
     <p>Age:{{u.age}}</p>
     <br />
   </div>
 </div>
Copy after login

Usage 5 (specify comparator as function):

// 先在Controller中定义function:myComparator, 此function将能匹配大小写不敏感的内容,但与comparator为false的情况不同的是,comparator必须匹配全文
 $scope.myComparator = function (expected, actual) {
   return angular.equals(expected.toLowerCase(), actual.toLowerCase());
 }
 <div ng-init="myArr = [{name:'Tom', age:}, {name:'Tom Senior', age:}, {name:'May', age:}, {name:'Jack', age:}, {name:'Alice', age:}]">
   Name:<input ng-model="yourName" />
   <div ng-repeat="u in myArr | filter:{name:yourName}:myComparator ">
     <p>Name:{{u.name}}</p>
     <p>Age:{{u.age}}</p>
     <br />
   </div>
 </div>
Copy after login

jsonFilter(json):

Method prototype:

Copy code The code is as follows:

function(object, spacing)

用法(将对象格式化成标准的JSON格式):

复制代码 代码如下:

{{ {name:'Jack', age: 21} | json}}

limitToFilter(limitTo):

方法原型:

复制代码 代码如下:

function(input, limit)

用法(选取前N个记录):

 <div ng-init="myArr = [{name:'Tom', age:}, {name:'Tom Senior', age:}, {name:'May', age:}, {name:'Jack', age:}, {name:'Alice', age:}]">
   <div ng-repeat="u in myArr | limitTo:">
     <p>Name:{{u.name}}
     <p>Age:{{u.age}}
   </div>
 </div>
Copy after login

lowercaseFilter(lowercase)/uppercaseFilter(uppercase):

方法原型:

复制代码 代码如下:

function(string)

用法:

China has joined the {{ "wto" | uppercase }}.
We all need {{ "MONEY" | lowercase }}.
Copy after login

numberFilter(number):

方法原型:

复制代码 代码如下:

function(number, fractionSize)

用法:

{{ "3456789" | number}}
<br />
{{ true | number}}
<br />
{{ 12345678 | number:1}}
Copy after login

orderByFilter(orderBy):

方法原型:

复制代码 代码如下:

function(array, sortPredicate, reverseOrder)

用法:

 <div ng-init="myArr = [{name:'Tom', age:, deposit: }, {name:'Tom', age:, deposit: }, {name:'Tom Senior', age:, deposit: }, {name:'May', age:, deposit: }, {name:'Jack', age:, deposit:}, {name:'Alice', age:, deposit: }]">
   <!--deposit前面的'-'表示deposit这列倒叙排序,默认为顺序排序
   参数reverseOrder:true表示结果集倒叙显示-->
   <div ng-repeat="u in myArr | orderBy:['name','-deposit']:true">
     <p>Name:{{u.name}}</p>
     <p>Deposit:{{u.deposit}}</p>
     <p>Age:{{u.age}}</p>
     <br />
   </div>
 </div>
Copy after login

自定义Filter

和Directive一样,如果内建的Filter不能满足你的需求,你当然可以定义一个专属于你自己的Filter。我们来做一个自己的Filter:capitalize_as_you_want,该Filter会使你输入的字符串中的首字母、指定index位置字母以及指定的字母全部大写。

方法原型:

复制代码 代码如下:

function (input, capitalize_index, specified_char)

完整的示例代码:

<!DOCTYPE>
 <html>
 <head>
   <script src="/Scripts/angular.js"></script>
   <script type="text/javascript">
     (function () {
       var app = angular.module('ngCustomFilterTest', []);
       app.filter('capitalize_as_you_want', function () {
         return function (input, capitalize_index, specified_char) {
           input = input || '';
           var output = '';
           var customCapIndex = capitalize_index || -;
           var specifiedChar = specified_char || '';
           for (var i = ; i < input.length; i++) {
             // 首字母肯定是大写的, 指定的index的字母也大写
             if (i === || i === customCapIndex) {
               output += input[i].toUpperCase();
             }
             else {
               // 指定的字母也大写
               if (specified_char != '' && input[i] === specified_char) {
                 output += input[i].toUpperCase();
               }
               else {
                 output += input[i];
               }
             }
           }
           return output;
         };
       });
     })();
   </script>
 </head>
 <body ng-app="ngCustomFilterTest">
   <input ng-model="yourinput" type="text">
   <br />
   Result: {{ yourinput | capitalize_as_you_want::'b' }}
 </body>
 </html>
Copy after login

好了,本篇讲了AngularJS中的Filter,看完这篇后,我们可以利用好Filter非常方便的使数据能按我们的要求进行展示,从而使页面变得更生动。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles