1. 程式人生 > >angular過濾器filter常用方法,自定義過濾器

angular過濾器filter常用方法,自定義過濾器

簡單介紹AngularJS過濾器filter用法,每個都將列出用法程式碼以便加深瞭解;

內建過濾器:

currency(貨幣)、date(日期)、filter(子串匹配)、json(格式化json物件)、limitTo(限制個數)、lowercase(小寫)、uppercase(大寫)、number(數字)、orderBy(排序)
用法:
1.currency(貨幣)
使用currency可以將數字格式化為貨幣,預設美元符號,你可以自己傳入所需的符號,如人民幣:

<!DOCTYPE html>
<html>
    <head>
        <meta
charset="utf-8" />
<title></title> <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script> </head> <body ng-app="myApp"> <div style="width: 500px;margin: 0 auto;"> <div ng-controller="homeCtr">
<p>
{{initNum | currency}}</p> <p>{{initNum | currency:'¥'}}</p> <ul ng-repeat="n in initArr"> <li>{{n | currency}}</li> </ul> </div> </div> <script
type="text/javascript">
var app = angular.module('myApp', []); app.controller('homeCtr',['$scope',function($scope){ $scope.initNum = 10; $scope.initArr = [10,20,30,40,50]; }]) </script> </body> </html>

這裡寫圖片描述
2.date(日期)
原生的js對日期的格式化能力有限,ng提供的date過濾器基本可以滿足一般的格式化要求。用法如下:

{{date | date : ‘yyyy-MM-dd hh:mm:ss EEEE’}}
引數用來指定所要的格式,y M d h m s E 分別表示 年 月 日 時 分 秒 星期,你可以自由組合它們。也可以使用不同的個數來限制格式化的位數。

<p>{{initDate | date:'yyyy/MM/dd hh:mm:ss EEEE'}}</p>
<ul ng-repeat="n in initDateArr">
    <li>{{n | date:'yyyy.MM.dd hh:mm:ss'}}</li>
</ul>
<!--時間日期格式自己改,基本滿足平常開發需求-->
//
$scope.initDate = '1523503158789';
$scope.initDateArr = [
    '1523502700688',
    '1523502953681',
    '1523502971335',
    '1523502980482'
]

這裡寫圖片描述
3 filter(匹配子串)
filter用來處理一個數組,然後可以過濾出含有某個子串的元素,作為一個子陣列來返回。可以是字串陣列,也可以是物件陣列。如果是物件陣列,可以匹配屬性的值。它接收一個引數,用來定義子串的匹配規則。

            <div ng-controller="homeCtr">
                <p>匹配屬性值中包含'張'的所有項</p>
                <ul ng-repeat="m in initMemberArr | filter:'張'">
                    <li>{{m.name}}</li>
                    <li>{{m.age}}</li>
                </ul>
                <p>匹配屬性值中包含 2的所有項</p>
                <ul ng-repeat="m in initMemberArr | filter:2">
                    <li>{{m.name}}</li>
                    <li>{{m.age}}</li>
                </ul>
                <p>匹配age屬性值中包含 2的所有項</p>
                <ul ng-repeat="m in initMemberArr | filter:{age:2}">
                    <li>{{m.name}}</li>
                    <li>{{m.age}}</li>
                </ul>
                <p>匹配id屬性值中包含 2,並且age屬性中包含2的項</p>
                <ul ng-repeat="m in initMemberArr | filter:{id:2} | filter:{age:2}">
                    <li>{{m.id}}</li>
                    <li>{{m.name}}</li>
                    <li>{{m.age}}</li>
                </ul>
                <p>匹配age屬性值 大於 30的項</p>
                <ul ng-repeat="m in initMemberArr | filter:ageFilt">
                    <li>{{m.id}}</li>
                    <li>{{m.name}}</li>
                    <li>{{m.age}}</li>
                </ul>
            </div>
        app.controller('homeCtr',['$scope',function($scope){
                $scope.initMemberArr = [
                    {
                        id:12,
                        name:'張一',
                        age:20,
                    },
                    {
                        id:23,
                        name:'張二',
                        age:31,
                    },
                    {
                        id:34,
                        name:'李三',
                        age:12,
                    },
                    {
                        id:45,
                        name:'張五',
                        age:33,
                    },
                    {
                        id:56,
                        name:'李六',
                        age:24,
                    }
                ]
                //定義返回age屬性大於30的方法
                $scope.ageFilt = function(arr){
                    return arr.age > 30;
                }
            }])

結果如下展示
這裡寫圖片描述
4.json(格式化json物件)
json過濾器可以把一個js物件格式化為json字串,沒有引數。一般也不會在頁面上用,或者在js中用,作用如JSON.stringify(),文章最後會寫出來在controller裡面使用過濾器;權當看看

<p>{{testObj}}</p>
<p>{{testObj | json}}</p>
<p>{{initMemberArr}}</p>
<p>{{initMemberArr | json}}</p>
$scope.initMemberArr = [
    {
        id:12,
        name:'張一',
        age:20,
    },
    {
        id:23,
        name:'張二',
        age:31,
    }
]
$scope.testObj = {a:1,b:2};

5 limitTo(限制陣列長度或字串長度)
limitTo過濾器用來擷取陣列或字串,接收一個引數用來指定擷取的長度,如果引數是負值,則從陣列尾部開始擷取。

                <p>擷取字串前三位</p>
                <p>{{initStr | limitTo:3}}</p>
                <p>initMemberArr 陣列擷取前兩項 ,每項的id擷取前四位</p>
                <ul ng-repeat = "m in initMemberArr | limitTo:2">
                    <li>{{m.id | limitTo:4}}</li>
                </ul>
                $scope.initMemberArr = [
                    {
                        id:'123456789',
                        name:'張一',
                        age:20,
                    },
                    {
                        id:'987654321',
                        name:'張二',
                        age:31,
                    },
                    {
                        id:'234765981',
                        name:'李三',
                        age:12,
                    }
                ]
                $scope.initStr = 'abcdefg';

這裡寫圖片描述
6 lowercase(小寫)
把資料轉化為全部小寫
7 uppercase(大寫)
把資料轉化為全部大寫

<p>{{str1 | uppercase}}</p>
<p>{{str2 | lowercase}}</p>

這兩個用法很簡單

$scope.str1 = 'abcf';
$scope.str2 = 'Abcd';

8 number(格式化數字)
number過濾器可以為一個數字加上千位分割,像這樣,123,456,789。同時接收一個引數,可以指定float型別保留幾位小數

                <p>{{num1 | number}}</p>
                <p>保留四位小數</p>
                <p>{{num2 | number:4}}</p>
                <p>保留兩位小數</p>
                <p>{{num3 | number:2}}</p>
$scope.num1 = 123456789;
$scope.num2 = 1357924680;
$scope.num3 = 1357.2498;

這裡寫圖片描述
9 orderBy(排序)
orderBy過濾器可以將一個數組中的元素進行排序,接收一個引數來指定排序規則,引數可以是一個字串,表示以該屬性名稱進行排序。可以是一個函式,定義排序屬性。還可以是一個數組,表示依次按陣列中的屬性值進行排序(若按第一項比較的值相等,再按第二項比較)

基本應用格式為:
ng-repeat=”item in itemList | orderBy:p1:p2”
引數p1可以是欄位名或自定義函式,p2指是否逆序,預設是false
//
多欄位排序:
ng-repeat=”item in itemList | orderBy:[orderIt,’name’,’-amount’]
第一個引數傳遞陣列,可以是自定義函式或欄位名,欄位名前面加“-”,代表倒排序。

        <p>按照id排序</p>
        <ul ng-repeat=" m in initMemberArr | orderBy : 'id'">
            <li>id:{{m.id}}-------name:{{m.name}}------age:{{m.age}}</li>
        </ul>
        <p>按照age排序</p>
        <ul ng-repeat=" m in initMemberArr | orderBy : 'age'">
            <li>id:{{m.id}}-------name:{{m.name}}------age:{{m.age}}</li>
        </ul>
        <p>按照name排序</p>
        <ul ng-repeat=" m in initMemberArr | orderBy : 'name'">
            <li>id:{{m.id}}-------name:{{m.name}}------age:{{m.age}}</li>
        </ul>
        <p>按照id降序</p>
        <ul ng-repeat=" m in initMemberArr | orderBy : 'id':true">
            <li>id:{{m.id}}-------name:{{m.name}}------age:{{m.age}}</li>
        </ul>
        <p>按照id降序,欄位前加-</p>
        <ul ng-repeat=" m in initMemberArr | orderBy : '-id'">
            <li>id:{{m.id}}-------name:{{m.name}}------age:{{m.age}}</li>
        </ul>
        <p>多欄位排序-按id升序,id一樣的,按age的倒序,大的排前;</p>
        <ul ng-repeat=" m in initMemberArr | orderBy :['id','-age']">
            <li>id:{{m.id}}-------name:{{m.name}}------age:{{m.age}}</li>
        </ul>
        $scope.initMemberArr = [
            {
                id:12,
                name:'張一',
                age:20,
            },
            {
                id:14,
                name:'張二',
                age:31,
            },
            {
                id:13,
                name:'李三',
                age:12,
            },
            {
                id:12,
                name:'老五',
                age:28,
            }
        ]

這裡寫圖片描述

自定義過濾器

    <p>將物件陣列中每一項的name改成順序的第幾名</p>
    <ul ng-repeat=" m in initMemberArr | joinStr">
        <li>id:{{m.id}}-------name:{{m.name}}------age:{{m.age}}</li>
    </ul>
    var app = angular.module('myApp', []);
    app.controller('homeCtr',['$scope',function($scope){
        $scope.initMemberArr = [
            {
                id:12,
                name:'張一',
                age:20,
            },
            {
                id:14,
                name:'張二',
                age:31,
            },
            {
                id:13,
                name:'李三',
                age:12,
            },
            {
                id:12,
                name:'老五',
                age:28,
            }
        ]

    }])
    app.filter('joinStr',function(){ //將物件陣列中每一項的name改成順序的第幾名,當然這在頁面直接用$index,更簡單,這只是為了看寫法;
       return function(arr){
             for(var i=0;i<arr.length;i++){
              arr[i].name = '第' + (i + 1) + '名';
           }
        return arr;
  }})

格式就是這樣,你的處理邏輯就寫在內部的那個閉包函式中。你也可以讓自己的過濾器接收引數,引數就定義在return的那個函式中,作為第二個引數,或者更多個引數也可以。

過濾器使用

1.使用內建的過濾器,可以像上面寫的,直接頁面模版中使用,

{{ expression | filter }};

可以多個filter連用,

{{ expression | filter1 | filter2 | … }}

filter可以接收引數,引數用 : 進行分割

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

2 在controller中使用,需要注入 $filter使用,
使用內建的過濾器

使用自定義的過濾器

            var app = angular.module('myApp', []);
            //注入$filter
            app.controller('homeCtr',['$scope','$filter',function($scope,$filter){
                $scope.initMemberArr = [
                    {
                        id:12,
                        name:'張一',
                        age:20,
                    },
                    {
                        id:14,
                        name:'張二',
                        age:31,
                    },
                    {
                        id:13,
                        name:'李三',
                        age:12,
                    },
                    {
                        id:12,
                        name:'老五',
                        age:28,
                    }
                ]
                //使用內建的過濾器
                $scope.resNum = $filter('currency')(123456789,'¥');
                console.log($scope.resNum);
                $scope.resStr = $filter('uppercase')('abcdefGh');
                console.log($scope.resStr);
                $scope.resSubStr = $filter('limitTo')('abcdefghi', 3);
                console.log($scope.resSubStr);
                ...
                ...
                ...
                //使用自定義的過濾器
                $scope.resArr = $filter('odditems')($scope.initMemberArr);
                console.log($scope.resArr);//只剩第一三項

            }]);

            //自定義過濾器,返回陣列的奇數項;
            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;
              }
            });

這裡寫圖片描述

看到這,差不多開發時filter過濾器用法都可以自己寫出來哈,只要js知識好些,複雜的過濾器,複雜的自定義過濾器,差不多都可以實現………………………