简体   繁体   English

获取ng-repeat内的图像尺寸并将其放入ng-repeat项目| AngularJS

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

I'm rendering some scope of objects via ng-repeat. 我通过ng-repeat渲染对象的某些范围。

HTML HTML

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

How I can get image clientWidth and clientHeight and put it in object product.imgSize inside ng-repeat? 如何获取图像clientWidthclientHeight并将其放在ng-repeat中的对象product.imgSize

What img-dimensions-bind-directuve should be? 什么是img-dimensions-bind-directuve

Currently I have: 目前我有:

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

On output each product must have imgSize.width and imgSize.height params. 输出时,每个product必须具有imgSize.widthimgSize.height参数。

Or maybe it is possible to do with onload function? 或者也许可以使用onload函数?

Please help. 请帮忙。

What about binding to product object directly without any additional ngModel. 在没有任何附加ngModel的情况下直接绑定到产品对象该怎么办? Like this: 像这样:

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

and HTML then: 然后HTML:

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

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

You can encode the dimensions as a json string. 您可以将维度编码为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}));
            });
        }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM