Why am I getting 404 error with ng-src even though the image appears?

I am displaying an image with ng-src

:

<img style="width: 100px" ng-src="{{absolutePath}}customImages/{{currentBook.idcode}}.png"/>

which is found and displayed fine, however in the Firebug console I get this error:

NetworkError: 404 Not Found - http://localhost/learntracker/customImages/.png"

as if it is done before the variables exist.

This HTML code exists internally <div ng-cloak ng-app="mainModule">

and ng-cloak

, I understand, to stop any execution before the variables exist.

Why does this error occur and how can you suppress it?

+3


source to share


2 answers


It looks like you can load data that populates the object asynchronously currentBook

. Therefore, during the previous digest cycle, the directive ng-src

would display the src for the image with no value for currentBook.idcode

, and as soon as it is filled in the area, the image is updated in another digest cycle. Thus, the previous reasons 404. You can put ng-if

on the image.

eg: -

<img style="width: 100px" ng-if="currentBook.idcode" 
     ng-src="{{absolutePath}}customImages/{{currentBook.idcode}}.png"/>

      

You can see a small demo implementation here

But this seems to have been fixed with the 1.3.x version of angular to prevent the src image from rendering before all the interpolations are expanded to get the values. Plnkr



ng-cloak

useful not to show short interpolation expression when loading angular.


More information (Courtesy @zeroflagL):

As of angular version 1.3.x, ng-src uses all or nothing interpolation ( addition to interpolateProvider ), meaning it will not expand the directive unless all related interpolations are allowed. You can see this mapping in the compile provider source .

ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),

      

+6


source


What you could do in this case is actually have a function in scope that creates an ULR for the image path:



<img style="width: 100px" ng-if="currentBook.idcode" ng-src="getImagePath(currentBook.idcode)">


var absolutePath = 'somepath/';
$scope.getImagePath = function(idcode) {
    return absolutePath + 'customImages/' + idcode + '.png';
}

      

0


source







All Articles