AngularJS的Filter用法详解

上一篇讲了自定义Directive,本篇是要讲到AngularJS的Filter。

 

Filter简介

Filter是用来格式化数据用的。

Filter的基本原型( '|' 类似于Linux中的管道模式):

{{ expression | filter }}

Filter可以被链式使用(即连续使用多个filter):

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

Filter也可以指定多个参数:

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

 

AngularJS内建的Filter

AngularJS内建了一些常用的Filter,我们一一来看一下。

currencyFilter(currency):

用途:格式化货币

方法原型:

function(amount, currencySymbol, fractionSize)

 用法:

1 {{ 12 | currency}}  <!--将12格式化为货币,默认单位符号为 '$', 小数默认2位-->
2 
3 {{ 12.45 | currency:'¥'}} <!--将12.45格式化为货币,使用自定义单位符号为 '¥', 小数默认2位-->
4 
5 {{ 12.45 | currency:'CHY¥':1}} <!--将12.45格式化为货币,使用自定义单位符号为 'CHY¥', 小数指定1位, 会执行四舍五入操作 -->
6 
7 {{ 12.55 | currency:undefined:0}} <!--将12.55格式化为货币, 不改变单位符号, 小数部分将四舍五入 -->

 

dateFilter(date):

用途:格式化日期

方法原型:

function(date, format, timezone)

用法:

<!--使用ISO标准日期格式 -->
{{ '2015-05-20T03:56:16.887Z' | date:"MM/dd/yyyy @ h:mma"}}

<!--使用13位(单位:毫秒)时间戳 -->
{{ 1432075948123 | date:"MM/dd/yyyy @ h:mma"}}

<!--指定timezone为UTC -->
{{ 1432075948123 | date:"MM/dd/yyyy @ h:mma":"UTC"}}

 

filterFilter(filter):

用途:过滤数组

方法原型:

function(array, expression, comparator)

用法1(参数expression使用String):

1 <div ng-init="myArr = [{name:'Tom', age:20}, {name:'Tom Senior', age:50}, {name:'May', age:21}, {name:'Jack', age:20}, {name:'Alice', age:22}]">
2     <!-- 参数expression使用String,将全文搜索关键字 'a' -->
3     <div ng-repeat="u in myArr | filter:'a' ">
4         <p>Name:{{u.name}}</p>
5         <p>Age:{{u.age}}</p>
6         <br />
7     </div>
8 </div>

用法2(参数expression使用function):

 1 // 先在Controller中定义function: myFilter
 2 $scope.myFilter = function (item) {
 3     return item.age === 20;
 4 };
 5 
 6 <div ng-repeat="u in myArr | filter:myFilter ">
 7     <p>Name:{{u.name}}</p>
 8     <p>Age:{{u.age}}</p>
 9     <br />
10 </div>

用法3(参数expression使用object):

1 <div ng-init="myArr = [{name:'Tom', age:20}, {name:'Tom Senior', age:50}, {name:'May', age:21}, {name:'Jack', age:20}, {name:'Alice', age:22}]">
2     <div ng-repeat="u in myArr | filter:{age: 21} ">
3         <p>Name:{{u.name}}</p>
4         <p>Age:{{u.age}}</p>
5         <br />
6     </div>
7 </div>

用法4(指定comparator为true或false):

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

用法5(指定comparator为function):

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

 

jsonFilter(json):

 方法原型:

function(object, spacing)

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

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

 

limitToFilter(limitTo):

 方法原型:

function(input, limit)

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

1 <div ng-init="myArr = [{name:'Tom', age:20}, {name:'Tom Senior', age:50}, {name:'May', age:21}, {name:'Jack', age:20}, {name:'Alice', age:22}]">
2     <div ng-repeat="u in myArr | limitTo:2">
3         <p>Name:{{u.name}}
4         <p>Age:{{u.age}}
5     </div>
6 </div>

 

lowercaseFilter(lowercase)/uppercaseFilter(uppercase):

 方法原型:

function(string)

用法:

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

 

numberFilter(number):

方法原型:

function(number, fractionSize)

用法:

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

 

orderByFilter(orderBy):

方法原型:

function(array, sortPredicate, reverseOrder)

用法:

 1 <div ng-init="myArr = [{name:'Tom', age:20, deposit: 300}, {name:'Tom', age:22, deposit: 200}, {name:'Tom Senior', age:50, deposit: 200}, {name:'May', age:21, deposit: 300}, {name:'Jack', age:20, deposit:100}, {name:'Alice', age:22, deposit: 150}]">
 2     <!--deposit前面的'-'表示deposit这列倒叙排序,默认为顺序排序
 3     参数reverseOrder:true表示结果集倒叙显示-->
 4     <div ng-repeat="u in myArr | orderBy:['name','-deposit']:true">
 5         <p>Name:{{u.name}}</p>
 6         <p>Deposit:{{u.deposit}}</p>
 7         <p>Age:{{u.age}}</p>
 8         <br />
 9     </div>
10 </div>

 

自定义Filter

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

方法原型:

function (input, capitalize_index, specified_char)

完整的示例代码:

 1 <!DOCTYPE>
 2 <html>
 3 <head>
 4     <script src="/Scripts/angular.js"></script>
 5     <script type="text/javascript">
 6         (function () {
 7             var app = angular.module('ngCustomFilterTest', []);
 8 
 9             app.filter('capitalize_as_you_want', function () {
10                 return function (input, capitalize_index, specified_char) {
11                     input = input || '';
12                     var output = '';
13 
14                     var customCapIndex = capitalize_index || -1;
15 
16                     var specifiedChar = specified_char || '';
17 
18                     for (var i = 0; i < input.length; i++) {
19                         // 首字母肯定是大写的, 指定的index的字母也大写
20                         if (i === 0 || i === customCapIndex) {
21                             output += input[i].toUpperCase();
22                         }
23                         else {
24                             // 指定的字母也大写
25                             if (specified_char != '' && input[i] === specified_char) {
26                                 output += input[i].toUpperCase();
27                             }
28                             else {
29                                 output += input[i];
30                             }
31                         }
32                     }
33 
34                     return output;
35                 };
36             });
37 
38         })();
39     </script>
40 </head>
41 <body ng-app="ngCustomFilterTest">
42     <input ng-model="yourinput" type="text">
43     <br />
44     Result: {{ yourinput | capitalize_as_you_want:3:'b' }}
45 </body>
46 </html>

 

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

 

参考资料

AngularJS官方文档:https://docs.angularjs.org/guide/filter

CodeSchool快速入门视频:http://campus.codeschool.com/courses/shaping-up-with-angular-js/intro

Fun with AngularJS filter: http://sarahbranon.com/post/69604997957/fun-with-angularjs-filters-part-1-the-filter

posted @ 2015-05-20 14:18  无上@诀  阅读(27924)  评论(0编辑  收藏  举报