我有一个数组或图像 URL,我用 ng-repeat
插入到页面中作为<img>
元素:
<ul>
<li ng-repeat="image in images">
<img src="{{image.src}}"/>
</li>
</ul>
我想在将这些图像插入 DOM 后从我的 Controller 中获取这些图像的尺寸(宽度和高度)。有没有办法遍历我的 $scope.images
数组并获取对表示其元素的 DOM 节点的引用?如果没有,最好的方法是什么?
最佳答案
您可以获得特定对象并直接在指令中更改它,因此如果您使用:ng-repeat="img in imgs"
,您将拥有 范围。指令中的 img
:
.directive('loadable', function () {
return {
link: function(scope, element, attrs) {
element.bind("load" , function(e){
// this is it:
scope.img.dimensions = {
height: element[0].naturalHeight,
width: element[0].naturalWidth
}
console.log(scope.img) // now the original object (in scope)
// has dimensions property!
});
}
}
});
示例:http://jsfiddle.net/XqeCr/1/
更新 并且建议将对象的操作包装在作用域的$aplly
方法调用中:
scope.$apply( function(){
scope.img.dimensions = {
height: element[0].naturalHeight,
width: element[0].naturalWidth
}
});
关于javascript - 如何从 Controller 获取表示 ngRepeat 中元素的 HTML 节点的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19292879/