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

接上一篇文章,本文将主要介绍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

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值