106

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?

Chris Smith
  • 18,244
  • 13
  • 59
  • 81
ssb
  • 7,422
  • 10
  • 36
  • 61

2 Answers2

230

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>
Gloopy
  • 37,767
  • 15
  • 103
  • 71
6

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

<div ng-style="{'background-image': 'url({{ image.source }})'}">...</div>
Syed
  • 15,657
  • 13
  • 120
  • 154
  • It is bad practice to use Interpolation with ngStyle. Reference: https://docs.angularjs.org/api/ng/directive/ngStyle – Abdul Rauf Jul 18 '17 at 07:23