Image Get Requests with AngularJS
I am storing the the source string of an image to be rendered in HTML in the AngularJS controller, however it yields a 404 before the Angular controller is initialized.
Here is the HTML:
<div ng-controller="Cont">
<img src="{{imageSource}}">
</div>
Angular controller:
var Cont = function($scope) {
$scope.imageSource = '/tests.png';
}
And the error I get (%7D%7D
corresponds to the {{
in the template).
GET https://localhost:9000/%7B%7BimageSource%7D%7D 404 (Not Found)
How can I prevent this from happening? That is, only load the image when the Angular controller has been initialized?
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>