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?
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With