angularJS---自訂過濾器,angularjs---過濾器

來源:互聯網
上載者:User

angularJS---自訂過濾器,angularjs---過濾器

AngularJS另一個特點就是提供了過濾器,可以通過操作UNIX下管道的方式,操作資料結果。

  通過使用管道,可以便於雙向的資料繫結中視圖的展現。

  過濾器在處理過程中,將資料變成新的格式,而且可以使用管道這種鏈式風格,還能接受附加的參數。

回到頂部  實現方式

  下面看一下如何定義聲明一個過濾器,首先依然是要建立我們自己的模組myAppModule

var myAppModule = angular.module("myApp",[]);

  接下來在模組的基礎上,建立過濾器:

myAppModule.filter("reverse",function(){            });

  其中reverse是過濾器的名字,後面跟著過濾器的方法聲明,在方法中返回另一個方法:

myAppModule.filter("reverse",function(){                return function(input,uppercase){                    var out = "";                    for(var i=0 ; i<input.length; i++){                        out = input.charAt(i)+out;                    }                    if(uppercase){                        out = out.toUpperCase();                    }                    return out;                }            });

  內部返回的方法包含了兩個參數,一個是輸入的值,就是我們過濾器接受的值。

  如果想要實現下面的過濾器:

  name | reverse

  則input就是其中name代表的值。

  後面的參數是可選的,我們這裡接受uppercase這個bool值,判斷是否要進行大小寫轉換。

  內部實現的代碼,就沒必要解釋了。最後返回過濾後的字串即可。

 

回到頂部  程式範例
<!doctype html><html ng-app="myApp">    <head>         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />         <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>    </head>    <body>        <div ng-controller="myAppCtrl">            name:{{ name }}<br>            reverse name:{{ name | reverse }}<br>            reverse&uppercase name:{{ name | reverse:true }}        </div>        <script type="text/javascript">            var myAppModule = angular.module("myApp",[]);            myAppModule.controller("myAppCtrl",["$scope",function($scope){                $scope.name = "xingoo";            }]);            myAppModule.filter("reverse",function(){                return function(input,uppercase){                    var out = "";                    for(var i=0 ; i<input.length; i++){                        out = input.charAt(i)+out;                    }                    if(uppercase){                        out = out.toUpperCase();                    }                    return out;                }            });        </script>    </body></html>

  運行結果

 





 

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.