Home » AngularJS 入門教學

[AngularJS]AngularJS 入門教學 - ngRepeat (二)

範例 1

上一篇已經見識過 ng-repeat 的威力的,但它其實還有額外提供一些可能會用到的變數。

像是假設筆者想在第一筆資料前方加個 span 區塊,然後顯示"第一筆"的訊息時,就能使用 ng-show 來搭配 $first 的變數:

1
2
3
4
<li ng-repeat="friend in friends | filter:search">
	{{ friend.name }}({{ friend.age }})
	<span ng-show="$first">[第一筆]</span>
</li>

ngrepeat-2-0

也能搭配 CSS 做運用呢!像是這樣:

1
<span class="friend-first-{{$first}}" ng-show="$first">[第一筆]</span>

然後 CSS 新增一個 .friend-first-true 的類別:

1
2
3
.friend-first-true {
	color: red;
}

預覽就會看到第一筆資料後的 span 元素變成紅字囉~
ngrepeat-2-1

其它的 span 元素的 class 就是除了 .ng-hide 之外,還會多一個是 .friend-first-false

除了 $first 之外,還有 $middle$last 兩個相關的變數可使用。一樣讓我們來新增一下 CSS:

1
2
3
4
5
6
.friend-middle-true {
	color: blue;
}
.friend-last-true {
	color: green;
}

然後把 li 中的內容修改為:

1
2
3
4
5
6
<li ng-repeat="friend in friends | filter:search">
	{{ friend.name }}({{ friend.age }})
	<span class="friend-first-{{$first}}" ng-show="$first">[第一筆]</span>
	<span class="friend-middle-{{$middle}}" ng-show="$middle">[中間的]</span>
	<span class="friend-last-{{$last}}" ng-show="$last">[最後一筆]</span>
</li>

這樣一來就會依相對的順序關係來套上效果了:
ngrepeat-2-2

不管筆數有多少筆,只要不是第一筆跟最後一筆的話,其它都算是 $middle 的範圍喔!

另外,它也有提供用來做出隔行效果的 $even$odd 變數。當然啦~第一筆資料的索引是 0,所以它算是偶數喔!

1
2
3
4
5
<li ng-repeat="friend in friends | filter:search">
	{{ friend.name }}({{ friend.age }})
	<span class="friend-odd-{{$even}}" ng-show="$even">[Even]</span>
	<span class="friend-even-{{$odd}}" ng-show="$odd">[Odd]</span>
</li>

加上相對應的 CSS:

1
2
3
4
5
6
.friend-even-true {
	color: blue;
}
.friend-odd-true {
	color: green;
}

很方便吧~
ngrepeat-2-3

那~如果在 ng-repeat 中有很多區塊都要能重覆產生的話,最直覺的是用一個父區塊來包裹。不過 ng-repeat 有另一種很特別的用法就是 ng-repeat-startng-repeat-end

1
2
3
4
5
6
7
8
9
<div class="well span6" style="margin-top:20px;" ng-controller="FriendsCtrl">
	<h2 ng-repeat-start="friend in friends">{{ friend.name }} </h2>
	<div class="alert alert-info">
		{{ friend.name }} <span class="badge badge-important">{{ friend.age }} 歲</span>
	</div>
	<div class="progress progress-striped active" ng-repeat-end>
		<div class="bar" style="width: {{ friend.age }}%;"></div>
	</div>
</div>

ng-repeat-startng-repeat-end 間的內容都能使用同一個 friend 的。
ngrepeat-2-4

什麼~週末不希望有作業!唔~練習可是不能等的,不過可以出簡單一點的。只要將我們剛剛弄出來的第二組區塊的 h2 標題加上奇數行變色吧!

範例 1

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

發表迴響