<img src=”path of image”>.
为了解决这个问题,我们需要使用ng-Src
。在使用 ng-Src
之前,我想给你重现一下这个错误是如何产生的
示例代码如下:
示例源码
Script.js
var testApp = angular .module("testModule", []) .controller("testController", function ($scope) { var animal = { name: "CAT", color: "White", picture: "/images/cat.jpg", };$scope.animal = animal;});Index.html
<html ng-app="testModule"> <head> <title></title> <script src="scripts/angular.min.js"></script> <script src="scripts/js/script.js"></script> </head> <body><div ng-controller="testController"> Name: {{animal.name}} <br /> Color: {{animal.color}} <br /> <img src="{{animal.picture}}" /></div> </body> </html>在上述例子 中,有一个
animal
类,它拥有三个属性: Name
, Color
和Picture
,且已经赋值了。使用模型绑定器,在页面上我使用了这些属性。 对于图片,我使用了 <img>
HTML标签 。
然后打开浏览器的控制台,就会看到这个错误。
无法加载资源:服务器响应状态为404 (Not Found)。
那么问题来了,为什么会出现这个错误?应该如何解决?
原因- 当DOM 被解析时,会尝试从服务器获取图片。 这时,src
属性上的 Angularjs 绑定表达式 {{ model }}
还没有执行,所以就出现了 404 未找到的错误。
解决方案- 解决的版本就是:在图片中使用ng-Src
代替src
属性,使用这个指令后,请求就只会在Angular执行这个绑定表达式之后才会发出。
使用ng-Src的示例如下:
<html ng-app="testModule"> <head> <title></title> <script src="scripts/angular.min.js"></script> <script src="scripts/js/script.js"></script> </head> <body> <div ng-controller="testController"> Name: {{animal.name}} <br /> Color: {{animal.color}} <br /> <img ng-src="{{animal.picture}}" /></div> </body> </html>现在你再打开浏览器的控制台,就不会出现:404 未找到, 这是因为使用了
ng-Src
。ng-Src-
这个指令覆盖了<img />
元素的src
原生属性。