接上一篇文章,本文將主要介紹angularjs中的模板鏈接,和圖像顯示?
首先,切換分支,啟動項目:
git checkout step-6 npm start
1.效果
相較於前一篇文章,明顯感覺多了圖片,那么這些圖片是怎么加載進去的呢?這里圖片各不一樣,如果用傳統的方式去加載圖片可能要寫很多代碼,這里看一下angularjs是如何實現的??
2.實現代碼
app/index.html
<ul class="phones"> <li ng-repeat="phone in phones | filter:query | orderBy:orderProp" class="thumbnail"> <a href="#/phones/{{phone.id}}" class="thumb"><img ng-src="{{phone.imageUrl}}"></a> <a href="#/phones/{{phone.id}}">{{phone.name}}</a> <p>{{phone.snippet}}</p> </li> </ul>
相較於上篇文章明顯發現只多了下面這一句:
<a href="#/phones/{{phone.id}}" class="thumb"><img ng-src="{{phone.imageUrl}}"></a>
那么先來看看數據源吧:
phones/phones.json
[
{
"age": 0,
"id": "motorola-xoom-with-wi-fi",
"imageUrl": "img/phones/motorola-xoom-with-wi-fi.0.jpg",
"name": "Motorola XOOM\u2122 with Wi-Fi",
"snippet": "The Next, Next Generation\r\n\r\nExperience the future with Motorola XOOM with Wi-Fi, the world's first tablet powered by Android 3.0 (Honeycomb)."
},
........
]
imageUrl中存了圖像的url路徑.這里可以發現 a href中現在用的是{{phone.id}}進行綁定的數據源頁面.
用ngSrc指令代替<img>
的src
屬性標簽就可以了。如果我們僅僅用一個正常src
屬性來進行綁定(<img class="diagram" src="{{phone.imageUrl}}">
),瀏覽器會把AngularJS的{{ 表達式 }}
標記直接進行字面解釋,並且發起一個向非法urlhttp://localhost:8000/app/{{phone.imageUrl}}
的請求。因為瀏覽器載入頁面時,同時也會請求載入圖片,AngularJS在頁面載入完畢時才開始編譯——瀏覽器請求載入圖片時{{phone.imageUrl}}
還沒得到編譯!有了這個ngSrc
指令會避免產生這種情況,使用ngSrc
指令防止瀏覽器產生一個指向非法地址的請求。
ngSrc指令的用法也比較簡單:
<IMG ng-src=""> ... </IMG>
src和ng-src的對比寫法:
The buggy way to write it: <img src="http://www.gravatar.com/avatar/{{hash}}"/> The correct way to write it: <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
為什么要這樣寫?官方解釋是:
The browser will fetch from the URL with the literal text {{hash}} until Angular replaces the expression inside {{hash}}.
瀏覽器將{{hash}}里的值,也即src屬性值替換成文本以后可能就停止干活了.
3.測試:
test/e2e/scenarios.js:
... it('should render phone specific links', function() { var query = element(by.model('query')); query.sendKeys('nexus'); element(by.css('.phones li a')).click(); browser.getLocationAbsUrl().then(function(url) { expect(url.split('#')[1]).toBe('/phones/nexus-s'); }); }); ...
測試結果:
amosli@amosli-pc:~/develop/angular-phonecat$ npm run protractor ... Finished in 6.789 seconds 3 tests, 6 assertions, 0 failures