Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs wait until div background-image shows

I have the following ng-repeat that grabs data from a $http.post call and stores it into $scope.data.

<div ng-repeat="key in [] | range:data.pages">
    <div class="pageBackground" id="page_{{ (key+1) }}" ng-style="{'background-image':'url(/images/{{data.id}}/{{(key+1)}}.png)'}">
    <!-- some random stuff here -->
</div>

What normal happens is the .pageBackground class will load before the background image does on the screen. I'd like nothing to show up until the background-image is actually loaded but I haven't been able to figure that out.

Does anyone have any suggestions?

like image 453
bryan Avatar asked Jan 26 '16 18:01

bryan


2 Answers

I'm not sure there is a real solution for your problem. A workaround could be to use the Image object, as explained in this answer. For example as a directive:

angular.module("yourModule").directive("showOnceBackgroundLoaded", [function () {
  return {
    restrict: "A",
    scope: false,
    link: function (scope, element, attributes) {
      element.addClass("ng-hide");
      var image = new Image();
      image.onload = function () {
        // the image must have been cached by the browser, so it should load quickly
        scope.$apply(function () {
          element.css({ backgroundImage: 'url("' + attributes.showOnceBackgroundLoaded + '")' });
          element.removeClass("ng-hide");
        });
      };
      image.src = attributes.showOnceBackgroundLoaded;
    }
  };
}]);

Use:

<div ng-repeat="key in [] | range:data.pages">
    <div class="pageBackground" id="page_{{ (key+1) }}" show-once-background-loaded="/images/{{data.id}}/{{(key+1)}}.png">
    <!-- some random stuff here -->
</div>
like image 99
sp00m Avatar answered Nov 10 '22 21:11

sp00m


Look here for a solution:

How can I tell when a CSS background image has loaded? Is an event fired?

what you do is you create an invisible partner element loading the same image. if and only if that image has been loaded (onload event) you show your other element, so for example:

<div ng-repeat="key in [] | range:data.pages" ng-init="_imageLoaded={}">
    <div ng-show="_imageLoaded[$index]" class="pageBackground" id="page_{{ (key+1) }}" ng-style="{'background-image':'url(/images/{{data.id}}/{{(key+1)}}.png)'}">
    <img ng-show="false" src="/images/{{data.id}}/{{(key+1)}}.png" onload="_imageLoaded[$index] = true;" />
    <!-- some random stuff here -->
</div>
like image 1
Patrick Kelleter Avatar answered Nov 10 '22 22:11

Patrick Kelleter