雖然 AngularJS 提供了蠻多個實用的過濾器(Filters),但總不可能包山包海都有各位需要的,因此我們在必要時就能來自訂專屬的過濾器囉。
筆者先建立一個簡單的模組(Module)及控制器(Controller):
1 2 3 4 5 | var myApp = angular.module('MyApp', []); myApp.controller('Ctrl', function($scope){ $scope.text = 'Hello Kitty'; }); |
然後再搭配個簡單的視圖(View):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <!doctype html> <html ng-app="MyApp"> <head> <meta charset="UTF-8"> <title>男丁格爾's 脫殼玩 - AngularJS</title> <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.min.js"></script> <script src="js/controller.js"></script> </head> <body> <div class="well span4" style="margin-top:20px;" ng-controller="Ctrl"> {{ text }} </div> </body> </html> |
這邊只是將 ,text 變數直接輸出而已,所以當預覽時就會看到 "Hello Kitty" 的字串了:
假設筆者想要將字串轉小並並將空白轉換成 - 的話,因為 AngularJS 並沒有提供這樣的過濾器,所以就讓我們自己動手來做一個。
.filter(name, filterFactory) 的基本用法很簡單:
1 2 3 4 5 | yourModule.filter('yourFilterName', function(){ return function(){ return result; }; }); |
在filterFactory 中透過閉包(Closure)的方式來建立處理用的函式。如果沒問題的話,就讓我們來看我們自己的過濾器吧:
1 2 3 4 5 | myApp.filter('clean', function(){ return function(str){ return str.toLowerCase().replace(/\s+/g, '-'); }; }); |
在裡面的函式所接收的第一個參數是指套上過濾器的變數值,例如當我們使用在 text 上的話,str 變數就是 text 變數的值:
1 | {{ text | clean }} |
當過濾器套用後:
就能看到字串都被轉小寫且空白也轉成 - 囉!
假設我們要能自訂用來取代空白的符號的話呢?那麼就需要接收額外的參數啦:
1 2 3 4 5 | myApp.filter('clean', function(){ return function(str, separator){ return str.toLowerCase().replace(/\s+/g, separator || '-'); }; }); |
我們除了基本的 str 變數之外,還多接收的一個用連結用的 separator 變數,而後面的 || 則是用來將 - 當預設的連結符號。
接著使用時就能自訂其它的連結符號,像是使用 +:
1 | {{ text | clean:'+' }} |
不知道各位是否還記得如何在使用過濾器時傳入參數呢?真的忘了的話,請先到 AngularJS 入門教學 - Filters (一) 再複習一下喔。
如果過程都正確的話,就能看到使用我們自訂的符號來連結的字串囉:
當然我們還能寫出更方便更複雜的過濾器,就看各位的需求是什麼了。ㄟ~筆者想要一個過濾器能將字串轉成駝峰式大小寫(Camel-Case),請各位幫忙寫看看囉!