您的位置:首页 > Web前端 > AngularJS

AngularJS学习--- AngularJS中模板链接和图像 ng-src step6

2014-05-09 02:12 507 查看
接上一篇文章,本文将主要介绍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的
{{ 表达式 }}
标记直接进行字面解释,并且发起一个向非法url
http://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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: