angularjs - 为什么 {{}} 在 src 属性中不起作用?为什么我需要 ngSrc?

标签 angularjs

这有效:

<a href="{{myAwesomeLink}}">It's a link. A dynamic one, at that.</a>

但这不是:

<img src="{{URLtoMyPerfectImage}}">

需要使用 ngSrc 来代替。我可以知道为什么会这样吗?我在 Handlebars.js 中使用“src”(或者是“href”?我不记得了)时遇到了类似的问题,并放弃了它(交付压力)。

这是一个普遍的浏览器问题还是类似的问题?

最佳答案

将答案延伸到我上面,同时

<a href="{{myAwesomeLink}}">It's a link. A dynamic one, at that.</a>

有效,但使用 Angular 动态创建链接时这不是最佳实践。任何时候在 anchor 标记中使用数据绑定(bind)时,都应该使用 ng-href 指令。因此 anchor 标记的代码应如下所示:

<a ng-href="{{myAwesomeLink}}">It's a link. A dynamic one, at that.</a>

直接来自 Angular 的文档:

Using Angular markup like in an href attribute makes the page open to a wrong URL, if the user clicks that link before angular has a chance to replace the with actual URL, the link will be broken and will most likely return a 404 error. The ngHref directive solves this problem.

这有助于我们理解 ng-src:因此

<img src="{{imgPath}}">

浏览器尝试加载图像,但 Angular 尚未替换 src 中的括号表达式,因此图像加载失败。通过使用

<img ng-src="{{imgPath}}">

您告诉浏览器等待加载图像,直到括号内的表达式被填充,从而加载正确的图像。

关于angularjs - 为什么 {{}} 在 src 属性中不起作用?为什么我需要 ngSrc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16648881/

相关文章:

javascript - mootools 1.4.2 和 angular 1.3 在 ie8 中一起玩得很好

javascript - Angular 和代码镜像

javascript - 使用 AngularJS "copy()"来避免引用问题

javascript - Angular JS ng-option 不适用于选择标签

javascript - 具有多个路由监听事件的 Angular 单页应用程序中的 SignalR

django - 使用 angular 向 django-rest 发送 DELETE 请求被解释为 OPTIONS

css - 如何在 AngularJS $routeProvider 中将样式表附加到 <head>?

angularjs - 在不使用 $rootScope 的情况下使用 Angular ui 路由器防止 stateChange

javascript - Angularjs $location 服务显然不解析 url?

angularjs - 用于力矩范围的 Angular 模块