How to access image properties after angular ng-repeat?

All we need is an easy explanation of the problem, so here it is.

I am trying to get image width and height of an image that I pull from server in order to apply proper style for it. So I am using ng-repeat to fill template :

<div ng-repeat="feed in feeds"> 
<div class="span2" >
    <img ng-src='{{feed.image_url}}'>
</div> ...

My question is how do I access img object so I can change parent div class? Or maybe what is the angular.js way of doing thing like that?

Edit : To be more specified. I want to access img object to get its width and height to calculate its size to apply style to parent div (currently with class span2).

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I don’t know what you’re trying to do, but it sounds like a job for a directive.

app.directive('styleParent', function(){ 
   return {
     restrict: 'A',
     link: function(scope, elem, attr) {
         elem.on('load', function() {
            var w = $(this).width(),
                h = $(this).height();

            var div = elem.parent();

            //check width and height and apply styling to parent here.

and you’d use it like so:

<img ng-src="imageFile" style-parent/>

EDIT: If you’re not using jquery, this will vary a little.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply