How to prevent ng-src to load image before data arrives?

后端 未结 4 528
暖寄归人
暖寄归人 2021-01-31 09:04

HTML:

 \"{{album.title}}\"

While running the app, it

相关标签:
4条回答
  • 2021-01-31 09:43

    Update March 2015

    Using Angular 1.3.x should make most custom data checks obsolete, since $interpolate now includes a flag "allOrNothing" that will wait for ALL bindings to be something other than undefined, before actually resolving the expression.

    So in this case, ng-src will only insert the src attribute once both album_images.image and album.cover_image are ready. Still, depending on your setup, album.title might not be ready yet, so if you want to wait for that you could still use the isDataAvailable() approach.

    Original Answer:

    Now that there's ng-if, one could try

    <img ng-if="isDataAvailable()" ng-src="{{plugins.filesPath.album_images.image}}{{album.cover_image}}" alt="{{album.title}}" />

    $scope.isDataAvailable = function(){
        // do your data checks here and
        // return true;
    }
    

    That way the image is only appended to the DOM as soon as isDataAvailable returns true and only then ng-src will kick in and try to get the file.

    Still, I'm pretty sure, 403 (Forbidden) is somewhat related to directory/file access restrictions on your server.

    0 讨论(0)
  • 2021-01-31 09:44

    Try to use the conditional pattern condition && true || false

    Therefore modify ng-src attribute like this:

    <img ng-src="{{ album && plugins.filesPath.album_images.image + album.cover_image || '' }}" alt="{{album.title}}" />
    

    With this change, the content of src attribute is empty until the data arrives.

    Source: Conditionally change img src based on model data

    0 讨论(0)
  • 2021-01-31 09:58

    I believe ng-src waits for it's value to change to apply a src value to the element. Did you try changing

    <img ng-src="{{plugins.filesPath.album_images.image}}{{album.cover_image}}"

    to

    <img ng-src="{{plugins.filesPath.album_images.image + album.cover_image}}" ?

    EDIT - revised answer

    As ng-src waits for the information in {{}} to change, it has no way of knowing if EVERY aspect of it is ready. I can think of two possible solutions:

    a) Make a url_when_ready() function, that takes strings as arguments and concatenates them, only returning a value if all of the strings are defined. Then do

    ng-src="{{url_when_ready([plugins.filesPath.album_images.image, album.cover_image])}}

    b) create a model $scope.album.cover_image_full that updates when $scope.album.cover_image is ready, and use that as the ng-src value

    0 讨论(0)
  • 2021-01-31 09:58

    like everyone else you can always show a loading sign before the image is completely loaded on the page. here is a fiddle containing the demo. you can use a different image in background before loading using .css('background-image','url('+ url_link_var +')');

    This is done and shown in Fiddle.

    0 讨论(0)
提交回复
热议问题