標籤:android style blog class code java
接上一篇文章,本文將主要介紹angularjs中的模板連結,和映像顯示?
首先,切換分支,啟動項目:
git checkout step-6npm 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‘); }); });...
測試結果:
[email protected]:~/develop/angular-phonecat$ npm run protractor ...Finished in 6.789 seconds3 tests, 6 assertions, 0 failures