過濾器,顧名思義,有些信息被會過濾到,不顯示給用戶。有些信息則會經過過濾后顯示給用戶。是的,在angularjs中,過濾器也是如此。
本節中,我們將展示過濾器在ng-repeat中是如何使用的。
為了更好的對頁面進行布局,我們首先引用前臺框架`bootstrap`。前面我們講過了使用bower下載angularjs,在此,我們使用bower下載`bootstrap`。
> npm是一款管理nodejs應用的包管理器,bower是一款管理第三方庫(這些庫并不依賴于任何服務器)的包管理器。用多了,自然也就清楚了。
## 下載bootstrap
`bower install bootstrap`為了和本教程保持一致,推薦使用`bower install bootstrap#3.3.6`,根據網速的不同,等待的時間也會各有不同。下載完成后目錄如下:
~~~
── app.module.js
├── bower_components
│?? ├── angular
│?? ├── bootstrap
│?? └── jquery
├── index.html
├── test.html
└── yun-zhi
├── hello-yunzhi.component.js
├── hello-yunzhi.template.html
├── phone-list.component.js
├── phone-list.template.html
└── yun-zhi.module.js
~~~
有人說,我并沒有讓它下載jquery呀,jquery怎么自己來了?是的,我們雖然沒有下載jquery的需求,但是我們下載的bootstrap依賴于jquery(確切的說是bootstrap一些組件的效果依賴于jquery),bower聰明的地方就在這里,它看到bootstrap后,就知道它依賴于jquery才能正常的工作,所以還為我們自動的下載了jquery。
> 沒錯,bower就是這么一款偉大的自動解決依賴關系的前端包管理工具。
下載完成后,我們在`index.html`中引用相關CSS文件。
`index.html`
~~~
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">
~~~
測試:

狀態碼:200 或 304 證明成功載入,路徑沒有問題。
## 增加查詢框
`yun-zhi/phone-list.template.html`
~~~
+ Search: <input ng-model="$ctrl.query" />
~~~
`ng-modle="$ctrl.query"`表示:該`input`輸入的信息,會實時的傳給$ctrl.query。即$ctrl.query的值會隨著`input`中值的變化而變化。
## 在ng-repeat中使用過濾器
~~~
<li ng-repeat="phone in $ctrl.phones | filter:$ctrl.query">
<span>{{phone.name}}</span>
<p>{{phone.snippet}}</p>
</li>
~~~
最后,我們增加下bootstrap的樣式。
`yun-zhi/phone-list.template.html`
~~~
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
Search:
<input ng-model="$ctrl.query" />
</div>
<div class="col-md-10">
<!--Body content-->
<ul class="phones">
<li ng-repeat="phone in $ctrl.phones | filter:$ctrl.query">
<span>{{phone.name}}</span>
<p>{{phone.snippet}}</p>
</li>
</ul>
</div>
</div>
</div>
~~~
然后刪除`index.html`中的`hello-yunzhi`標簽。
效果:

<a class="btn btn-info" href="http://angular.github.io/angular-phonecat/step-5/app/" target="_blank">查看DEMO(官方)</a>
- 前言
- 第一章:準備知識
- 第一節:GIT
- 第二節:Node.js
- 第三節:http-server
- 第四節:bower
- 第五節:firefox+chrome
- 第二章:官方示例教程
- 第零節:Hello Yunzhier
- 第一節:靜態模板
- 第二節:MVC
- 回調函數
- 第三節:組件
- 第四節:重構組件
- 2.4.1 調用組件
- 2.4.2 規劃目錄結構
- 2.4.3 剝離V層
- 2.4.4 大話測試
- 第五節:循環過濾器
- 第六節:雙向數據綁定
- 第七節:XHR與依賴注入
- 第八節:添加縮略圖
- 第九節:模擬頁面跳轉
- 2.9.1 使用bower
- 2.9.2 使用grunt
- 第十節:完善手機詳情頁
- 第十一節:自定義過濾器
- 第十二節:行為處理
- 第十三節:封裝請求
- 第十四節:應用動畫
- 第十五節:總結
- 第三章:菜譜管理示例
- 第四章:總結