AngularJS显示图片需要注意的地方

AngularJS显示图片的时候, 不要直接用src, 官方原话是这样的

1
2
3
4
Using AngularJS markup like {{hash}} in a src attribute doesn't work right: The
browser will fetch from the URL with the literal text {{hash}} until AngularJS
replaces the expression inside {{hash}}. The ngSrc directive solves this
problem.

如果直接用src的话, AngularJS在根据src显示图片之前会先请求一次src里面的纯字符串内容, 比如我写

1
<img src="{{pic.url}}" />

刷新页面会发现一个奇怪的网络请求, 虽然图片还是能正常显示

1
http://127.0.0.1:8080/%7B%7Bpic.url%7D%7D

其实就是

1
http://127.0.0.1:8080/{{pic.url}}

而用

1
<img ng-src="{{pic.url}}" />

则不会有这问题