我想访问当前htmlimg
元素的height和width属性,以ngClass
基于该属性动态应用。
我有此代码的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>
我正在使用AngularJSngClass
动态应用
$scope.myclass = function(element) {
return (element.width > element.height ? 'landscape' : 'portrait');
}
我无法读取width和height属性。你有什么建议吗?
您尝试的问题在于,与常规HTML事件属性(例如和)不同onclick
,ngClass
它们具有不同的调用上下文。确切地说,this
指向当前作用域对象。
在您的情况下,您应该编写一个自定义指令来读取/操作DOM元素。例如,简单的指令可能看起来像:
app.directive('dimentionClass', function() {
return {
link: function(scope, element) {
var img = element[0];
img.onload = function() {
img.className = img.width > img.height ? 'landscape' : 'portrait';
}
}
};
});
您将像这样使用它:
<img ng-src="{{album.thumbnail.image_path}}" dimention-class />
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句