view raw
Mauricio Betancur Molina Mauricio Betancur Molina - 10 months ago 72
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}" />

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


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.



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


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();