在 ng-repeat 中获取图像尺寸并将其放入 ng-repeat item | AngularJS

Get image dimensions inside ng-repeat and put it in ng-repeat item | AngularJS

我正在通过 ng-repeat 渲染一些范围的对象。

HTML

<tr ng-repeat="product in products">
    <td><img ng-src="{{product.img_thumb}}" ng-model="product.imgSize" img-dimensions-bind-directive></td>
</tr>

如何获取图像 clientWidthclientHeight 并将其放入 ng-repeat 中的对象 product.imgSize 中?

img-dimensions-bind-directuve 应该是什么?

目前我有:

app.directive('imgDimensionsBindDirective', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            element.bind('load', function() {
                ngModel.$setViewValue(element[0].clientWidth);
                // but how bind height ??
                // element[0].clientHeight
            });
        }
    }
});

输出时每个 product 必须有 imgSize.widthimgSize.height 参数。

或者也许可以使用 onload 函数?

请帮忙。

如果不使用任何额外的 ngModel 直接绑定到产品对象呢?像这样:

app.directive('imgDimensionsBindDirective', function() {
    return {
        restrict: 'A',
        scope: {
            product: '=imgDimensionsBindDirective'
        },
        link: function(scope, element, attrs) {
            element.bind('load', function() {
                scope.product.imgSize = {
                    width: element[0].clientWidth,
                    height: element[0].clientHeight
                };
                scope.$apply();
            });
        }
    }
});

和HTML然后:

<tr ng-repeat="product in products">
    <td><img ng-src="{{product.img_thumb}}" img-dimensions-bind-directive="product"></td>
</tr>

演示http://plnkr.co/edit/8xGZ8LrKL6NB22ZX8Mpz?p=preview

您可以将维度编码为 json 字符串。

app.directive('imgDimensionsBindDirective', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            element.bind('load', function() {
                ngModel.$setViewValue(angular.toJson({width: element[0].clientWidth,height:  element[0].clientHeight}));
            });
        }
    }
});