AngularJS 中的 ng-Src 指令






4.80/5 (3投票s)
在本文中,你将学习 AngularJS 中的 ng-Src 指令。
引言
在开发过程中,我们经常需要在页面上显示图片。有时,图片路径来自客户端脚本语言(也可能来自数据库)。
现在是 AngularJS 时代。当我们使用 AngularJS 并且想要在页面上显示图片时,我们简单地使用 <img src=”图片路径”>。
如果我们考虑一个输出结果,它工作正常,对此毫无疑问,但在浏览器控制台中,我们会收到 404(未找到)错误。
为了消除这种错误,我们有 ng-Src
。在继续 ng-Src
之前,我想向你展示一下这个错误是如何产生的。请查看下面的示例
Using the Code
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(未找到)。
现在,问题来了,为什么会出现这个错误,解决方案是什么?
原因 - 当 DOM 被解析时,它会尝试从服务器检索图片。此时,AngularJS 绑定表达式 {{ model }},它被指定在 src
属性中,由于 AngularJS 尚未评估该表达式,因此无法评估,从而导致 404 未找到错误。
解决方案 - 解决方案是 ng-Src
。在图片中使用 ng-Src
代替 src
属性,使用这个 AngularJS 指令,请求将在 AngularJS 评估绑定表达式后才发出。
对于 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
属性。