Reputation: 1583
I'm rendering some scope of objects via 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>
How I can get image clientWidth
and clientHeight
and put it in object product.imgSize
inside ng-repeat?
What img-dimensions-bind-directuve
should be?
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.
Or maybe it is possible to do with onload
function?
Please help.
Upvotes: 1
Views: 1193
Reputation: 3426
You can encode the dimensions as a json string.
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}));
});
}
}
});
Upvotes: 0
Reputation: 193271
What about binding to product object directly without any additional 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:
<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
Upvotes: 2