Reputation: 383
I want to access height and width property of current html img
element to apply ngClass
dynamically based on property.
I have this code for html
<div class="cfg-pg-outer-box" ng-repeat="album in album_list">
<div class="cfg-pg-photo-box">
<img ng-src="{{album.thumbnail.image_path}}" ng-class="myclass(this)">
</div>
</div>
I am using AngularJS to apply ngClass
dynamically
$scope.myclass = function(element) {
return (element.width > element.height ? 'landscape' : 'portrait');
}
I am not able to read width and height properties. Do you have any suggestion?
Upvotes: 2
Views: 1753
Reputation: 77
var width = document.getElementById('<Element's ID>').offsetWidth;
var height= document.getElementById('<Element's ID>').offseHeight;
Upvotes: 1
Reputation: 15501
var height = document.body.clientHeight;
var width = document.body.clientWidth;
EDIT:
In response to your comment, try using:
var element = document.getElementById("elementId");
var height = element.style.height;
var width = element.style.width;
EDIT2:
You might also wanna try:
document.getElementById(id_attribute_value).offsetHeight;
and/or
document.getElementById(id_attribute_value).clientHeight;
Upvotes: 0
Reputation: 51
You need to use $scope.$apply, otherwise any changes to $scope made in non-Angular event handlers won't be processed properly:
$scope.myclass = function(element) {
$scope.image.width = img.width;
$scope.image.height = img.height;
$scope.image.path = $scope.imageurl;
$scope.$apply();
return (this.width > this.height ? 'landscape' : 'portrait');
}
Upvotes: 1
Reputation: 193271
The problem with your attempt is that unlike regular HTML event attributes like onclick
, ngClass
and similar have different context of invocation. To be exact this
points to current scope object.
In your case you should write a custom directive to read/operate with DOM element. For example simple directive can look like:
app.directive('dimentionClass', function() {
return {
link: function(scope, element) {
var img = element[0];
img.onload = function() {
img.className = img.width > img.height ? 'landscape' : 'portrait';
}
}
};
});
and you will use it like this:
<img ng-src="{{album.thumbnail.image_path}}" dimention-class />
Demo: http://plnkr.co/edit/GtklqTUvtbFxb6AFuz4S?p=preview
Upvotes: 2