Mauricio Betancur Molina Mauricio Betancur Molina - 4 months ago 31
AngularJS Question

Angular ng-class depending on image aspect

How can I set a ng-class (inside ng-repeat) depending on image aspect ratio?

something like...

<div ng-repeat="img in images" style="width: 100px; height: 100px;">
<img ng-src="{{img}}" ng-class="{'wide': img.width/img.height > 1, 'tall': img.width/img.height <= 1}" />
</div>


EDIT: CSS object-fit doesn't work for me because of IE... :(

Answer

The main problem here is waiting for the image to load before setting the width / height properties on the img json object. So something like this will work.

Important: Scope.apply - Because you are altering the scope in a non-angular context, i.e. in jQuery you need to call scope.apply so the digest-watch cycle occurs and the variables get set up correctly.

Plunker

HTML:

<img ng-src="{{img}}" image-set-aspect ng-class="{'wide':    img.width/img.height > 1, 'tall': img.width/img.height <= 1}" />

Directive:

app.directive('imageSetAspect', function() {
    return {
        scope: false,
        restrict: 'A',
        link: function(scope, element, attrs) {
        element.bind('load', function() {
            // Use jquery on 'element' to grab image and get dimensions.
            scope.$apply(function() {
              scope.imageMeta.width = $(element).width(); 
              scope.imageMeta.height = $(element).height(); 
              console.log(scope.$parent.imageMeta);
            });
        });
        }
    };
});
Comments