gpt4 book ai didi

javascript - 如果我使用 src 而不是 ng-src,angular 仍然如何渲染图像?

转载 作者:行者123 更新时间:2023-11-30 11:59:27 25 4
gpt4 key购买 nike

根据 Angular 文档及其解释,我们应该使用 ng-src而不是 src在图像标记中,图像 url 是一个 Angular 表达式。

例如<img ng-src="{{country.flagURL}}" width="100">

但在我的例子中,如果我使用 src ,浏览器仍然呈现图像。在控制台中,我可以看到一个失败的图像调用,它试图访问像 .../Desktop/%7B%7Bcountry.flagURL%7D%7D 这样的确切表达式。

但是,稍后还有另一个图像调用,它是从 angular.js 发起的,它实际渲染图像并将其显示在浏览器中。

所以我的问题是 - ng-src 有什么用?如果使用 src 也能达到同样的效果?看起来只有一个额外的网络调用会在那里。
当我不使用 ng-src 时,渲染图像的 Angular 到底发生了什么? ?

下面是我的代码片段。你可以跑过去看看。

<html ng-app="countryApp">
<head>
<meta charset="utf-8">
<title>Angular.js Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
<script>
var countryApp = angular.module('countryApp', []);
countryApp.controller('CountryCtrl', function ($scope, $http){
data = [
{
"name": "China",
"population": 1359821000,
"flagURL": "https://upload.wikimedia.org/wikipedia/commons/f/fa/Flag_of_the_People%27s_Republic_of_China.svg"
},
{
"name": "India",
"population": 1205625000,
"flagURL": "https://upload.wikimedia.org/wikipedia/en/4/41/Flag_of_India.svg"
},
{
"name": "United States of America",
"population": 312247000,
"flagURL": "https://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg"
}
];
$scope.countries = data;
});

</script>
</head>
<body ng-controller="CountryCtrl">
<table>
<tr>
<th>Country</th>
<th>Population</th>
<th>Flag</th>
</tr>
<tr ng-repeat="country in countries">
<td>{{country.name}}</td>
<td>{{country.population}}</td>
<td><img src="{{country.flagURL}}" width="100"></td>
</tr>
</table>
</body>
</html>

最佳答案

<img ng-src="{{country.flagURL}}" width="100">

在计算 ng-src 中的表达式之前,Angular 不会加载图像。

但是,

<img src="{{country.flagURL}}" width="100">

浏览器尝试使用原始(未评估)表达式加载图像,这导致对服务器的 GET 请求失败。但是,一旦 Angular 加载并评估 src 标签下的表达式,浏览器就会使用新的 url 值重新呈现图像标签。

所以简而言之,ng-src 只是停止加载图像,直到 angular 执行表达式以避免初始无效请求(具有无效 URL)。检查 ng-src 的实现 here .它只是添加了 src 标签图像,导致对图像的 GET 请求。

关于javascript - 如果我使用 src 而不是 ng-src,angular 仍然如何渲染图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37046546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com