使用 AngularJS 获取图像请求

我正在 AngularJS 控制器中存储要用 HTML 呈现的图像的源字符串,但是在初始化 Angular 控制器之前它会生成一个404。

下面是 HTML:

 <div ng-controller="Cont">
<img src="{{imageSource}}">
</div>

角度控制器:

 var Cont = function($scope) {
$scope.imageSource = '/tests.png';
}

我得到的错误(%7D%7D对应于模板中的 {{)。

 GET https://localhost:9000/%7B%7BimageSource%7D%7D 404 (Not Found)

如何防止这种情况发生? 也就是说,只有在角度控制器初始化时才加载图像?

32512 次浏览

Try replacing your src with ng-src for more info see the documentation:

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

 <div ng-controller="Cont">
<img ng-src="\{\{imageSource}}">
</div>

If someone is searching the solution for styling background-image then use this:

<div ng-style="{'background-image': 'url(\{\{ image.source }})'}">...</div>