Home » AngularJS 入門教學

[AngularJS]AngularJS 入門教學 - Filters (三)

範例 1

接下來筆者會繼續使用上一篇的表格資料來介紹 orderBylimitTo 這兩個過濾器(Filters)

orderBy

可以將陣列中的元素進行依指定的屬性來排序。

一樣是用上一篇的表格來當範例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<div class="span7" style="margin-top:20px;" ng-controller="TableFilterCtrl">
	<table class="table table-striped table-bordered">
		<thead>
			<tr>
				<td>編號</td>
				<td>名稱</td>
				<td>年齡</td>
				<td>專長</td>
			</tr>
		</thead>
		<tbody>
			<tr ng-repeat="friend in friends">
				<td>{{ $index + 1 }}</td>
				<td>{{ friend.name }}</td>
				<td>{{ friend.age }}</td>
				<td>{{ friend.skills.join(', ') }}</td>
			</tr>
		</tbody>
	</table>
</div>

目前只有單純的依物件在陣列中的順序來一一顯示出來而已,並沒有多加上其它過濾器(Filters)
filters-3-0

假設筆者想依年齡來進行排序顯示的話,那麼可以在使用 ng-repeat 時加上 orderBy 來進行資料排序的轉換:

1
<tr ng-repeat="friend in friends | orderBy:'age'">

這邊要特別注意一下,我們在 orderBy 加上要排序的屬性名稱,同時還多加上單引號來讓它變成字串的型態喔!
filters-3-1

因為我們指定的是 'age',所以預設是由小排到大,若是想由大排到小的話,可以把 'age' 改成 '-age' 就可以囉:

1
<tr ng-repeat="friend in friends | orderBy:'-age'">

或者是再多傳入一個 bool 參數來指定是否反向排序:

1
<tr ng-repeat="friend in friends | orderBy:'age':true">

這兩種方式出來的結果都是一樣的:
filters-3-2

limitTo

產生一個只包含指定數量的新的陣列或是字串。

讓我們將表格的內容指限制顯示 5 筆:

1
<tr ng-repeat="friend in friends | limitTo:5">

這樣會在產生新的陣列後再進行 ng-repeat 的動作:
filters-3-3

若限制的值是負數的話,資料筆數將從後面來取得:

1
<tr ng-repeat="friend in friends | limitTo:-5">

filters-3-4

最後,再補充一點,這些過濾器(Filters)是可以組合起來使用的,只要每組些過濾器(Filters)間使用 | 來區隔就可以了。例如,筆者想要用年齡來排序,然後最多顯示 5 筆的話,就可以寫成:

1
<tr ng-repeat="friend in friends | orderBy:'age' | limitTo:5">

filters-3-5

筆者一共花了 3 篇來介紹 AngularJS內建的過濾器(Filters),為了讓大家能有機會好好練習一下,我們這次的作業就是在以上一篇的範例為基礎之下,請各位將範例加強為:
1.點擊標題可以進行資料排序,再點一次就變成反向排序。
2.多加一個輸入方塊可以用來限制顯示筆數。
3.讓名字轉大寫。

加油囉~若有任何問題就請直接留言發問!

範例 1

檔案描述
基本的範例檔案(免空) 開始下載
基本的範例檔案 會員限定

2 筆針對 [AngularJS]AngularJS 入門教學 - Filters (三) 的迴響

  1. 您好:
    下列是我自己寫的controller

    檢視原始碼 JavaScript
    1
    2
    3
    4
    5
    6
    
    var IndexCtrl = ['$scope', '$http', '$filter', function ($scope, $http, $filter) {
        $http.get(setting.sourceUrl).success(function (result) {
            $scope.customers = result;
        });
        //$filter('filter')($scope.customers, $scope.query);
    }];

    透過利用$http來讀取後端所提供的json陣列
    前端有一個輸入過濾的輸入框,ng-model="query"
    利用註解掉的語法來想達到在controller裡執行過濾的動作
    但是沒有任何效果
    而您的的文章中的範例也都是以在html中撰寫filter為主
    因此是否能請您寫個在controller執行filter的範例呢?
    謝謝

發表迴響