W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
在使用 AngularJS 的過程中會遇到一些特殊的數(shù)據(jù)處理,你可以通過采用 AngularJS 篩選器的方式來對不同的數(shù)據(jù)處理實現(xiàn)想要達到的效果。
在這一步中,你將學(xué)會如何創(chuàng)建你自己的自定義顯示篩選器。
把工作空間重置到第九步
git checkout -f step-9
刷新你的瀏覽器或在線檢查這一步:Step 9 Live Demo
下面列出了第八步和第九步之間最重要的區(qū)別。你可以在GitHub上看到完整的差異。
為了創(chuàng)建一個新篩選器,你即將創(chuàng)建一個phonecatFilters
模塊,并用這個模塊注冊你的自定義濾鏡:
app/js/filters.js
:
angular.module('phonecatFilters', []).filter('checkmark', function() {
return function(input) {
return input ? '\u2713' : '\u2718';
};
});
我們的篩選器的名字是“checkmark”。input
要么估值為true
,要么估值為false
,而且會返回我們選中用來代表true和false的兩個unicode字符之一(\u2713
->?代表true,\u2718
-> ?代表false)。
現(xiàn)在我們的篩選器已經(jīng)準備好了,我們需要注冊phonecatFilters
模塊作為我們的主phonecatApp
模塊的依賴性。
app/js/app.js
:
...
angular.module('phonecatApp', ['ngRoute','phonecatControllers','phonecatFilters']);
...
因為篩選器生存在app/js/filters.js
文件夾中,我們需要在我們的布局模板中包含這個文件。
app/index.html
:
...
<script src="/attachments/image/wk/angularjs/controllers.js"></script>
<script src="/attachments/image/wk/angularjs/filters.js"></script>
...
在Angular模板中使用篩選器的句法如下所示:
{{ expression | filter }}
讓我們在手機詳情模板中采用這個篩選器:
app/partials/phone-detail.html
:
...
<dl>
<dt>Infrared</dt>
<dd>{{phone.connectivity.infrared | checkmark}}</dd>
<dt>GPS</dt>
<dd>{{phone.connectivity.gps | checkmark}}</dd>
</dl>
...
篩選器,就像任何別的組件,必須被測試,而且寫這些測試很容易。
test/unit/filtersSpec.js
:
describe('filter', function() {
beforeEach(module('phonecatFilters'));
describe('checkmark', function() {
it('should convert boolean values to unicode checkmark or cross',
inject(function(checkmarkFilter) {
expect(checkmarkFilter(true)).toBe('\u2713');
expect(checkmarkFilter(false)).toBe('\u2718');
}));
});
});
我們必須在執(zhí)行任何篩選器測試之前調(diào)用beforeEach(module('phonecatFilters'))
。這種調(diào)用把我們的phonecatFilter
模塊載入到注入器,以測試運行。
注意我們將調(diào)用助手函數(shù)inject(function(checkmarkFilter) { ... })
,從而獲得訪問我們想要測試的文件。參見angular.mock.inject()。
注意在注入的時候,后綴Filter
會追加到你的篩選器名稱中。參見篩選器指南?部分,在那里是概述。
你現(xiàn)在必須在Karma選項卡中看到以下的輸出:
Chrome 22.0: Executed 4 of 4 SUCCESS (0.034 secs / 0.012 secs)
讓我們用一些內(nèi)建的Angular篩選器來做實驗,并把以下綁定添加到index.html
:
{{ "lower cap string" | uppercase }}
{{ {foo: "bar", baz: 23} | json }}
{{ 1304375948024 | date }}
{{ 1304375948024 | date:"MM/dd/yyyy @ h:mma" }}
我們可以創(chuàng)建一個模塊,帶有一個輸入元素,并把它與一個篩選綁定結(jié)合起來。向index.html添加以下代碼:
<input ng-model="userInput"> Uppercased: {{ userInput | uppercase }}
現(xiàn)在你已經(jīng)學(xué)會了如何編寫并測試一個自定義篩選器,前往第十步 事件處理函數(shù)以學(xué)習(xí)我們可以如何用Angular繼續(xù)豐富手機詳情頁面。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: