When I use an angularjs component to create stylized pictures, the style is not applied correctly on the first visit to a page (refreshing the page shows the correct style). The CSS that should be applied is generated dynamically based on the height and width properties of the image being styled.
I am seeking advice on why the CSS works upon reload but not during the initial load, as well as how to resolve this issue so that the CSS is properly applied the very first time the page is loaded. Thank you in advance!
Here's my HTML code for creating a stylized picture:
<stylized-picture image-source="someImage.jpg"></stylized-picture>
The implementation of the stylizedPicture component:
.component('stylizedPicture', {
templateUrl: 'src/components/stylized-picture.template.html',
bindings: {
imageSource: '@imageSource',
},
controller: 'StylizedPictureController as stylizedPictureController'
});
The content of stylized-picture.template.html:
<div ng-style="stylizedPictureController.outerCSS">
<div ng-style="stylizedPictureController.innerCSS"></div>
<div ng-style="stylizedPictureController.imgDivCSS">
<img ng-src="{{stylizedPictureController.imageSource}}">
</div>
</div>
</div>
About the stylizedPictureController: The CSS adjustments are dependent on the dimensions of the image.
.controller('StylizedPictureController', StylizedPictureController);
StylizedPictureController.$inject = ['$scope'];
function StylizedPictureController($scope) {
var ctrl = this;
ctrl.$onChanges = function() {
var img = new Image();
img.addEventListener("load", function() {
ctrl.imgWidth = img.naturalWidth;
ctrl.imgHeight = img.naturalHeight;
// Placeholder logic for styling image based on its dimensions
var paddingBottom = 100;
ctrl.paddingBottom = paddingBottom;
ctrl.outerCSS = {"padding-bottom: " + paddingBottom + "%"};
ctrl.innerCSS = {"padding-bottom: " + paddingBottom + "%"};
ctrl.imgDivCSS = {"padding-bottom: " + paddingBottom + "%"};
});
img.src = ctrl.imageSource;
};
};
I have experimented with using image.onLoad()
instead of ctrl.$onChanges
or the img
event listener, but encountered similar outcomes. Additionally, attempts to set ng-style
inline like
ng-style="{'padding-bottom': stylizedPictureController.paddingBottom}"
did not yield any differences.