[英]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? 如何获取图像
clientWidth
和clientHeight
并将其放在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.width
和imgSize.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.