[英]How can I show images on load with Angularjs?
I am trying to hide an image until it is loaded, and then use the onload
method to call a jQuery function that shows it. 我试图隐藏图像,直到它被加载,然后使用onload
方法调用显示它的jQuery函数。 I use the angular ng-repeat
property $index
to assign a unique ID to each image div. 我使用有角的ng-repeat
属性$index
为每个图像div分配一个唯一的ID。 The $index
property works, since all my images have ID's like img0
, img1
, and so on. $index
属性可以正常工作,因为我的所有图像都有ID,例如img0
, img1
等等。 My problem is that onload
is not passing the angular variable, which contains the unique div ID, to my function. 我的问题是onload
没有将包含唯一div ID的angular变量传递给我的函数。 Are angular variables unable to be used inside the onload
method? 不能在onload
方法中使用角度变量吗? If not, how can I make it so? 如果没有,我该怎么做?
<div class="hello" ng-repeat="artist in artists" ng-hide="!artiste">
<div class="paintings" id="img{({$index})}" style="display:none;">
<a href="{({ artist.fields.link })}">
<img src="{({ artist.fields.link })}" onload="showImageDiv(img{({$index})})" />
</a>
<h3> {({ artist.fields.title })} </h3>
</div>
</div>
<script>
function showImageDiv(imageDivId){ // never receives imageDivId
$('#' + imageDivId).show();
};
</script>
It doesn't work this way - attribute onload is not a directive, so its value is not parsed by angular. 这种方式行不通-属性onload不是指令,因此它的值不会被angular解析。 You could use a custom directive though, for example (assuming there is a "myModule" module defined): 不过,您可以使用自定义指令,例如(假设定义了“ myModule”模块):
angular.module("myModule").directive("showOnLoad", function() {
return {
link: function(scope, element) {
element.on("load", function() {
scope.$apply(function() {
scope.artist.visible = true;
});
});
}
};
});
It would set the artist.visible field value to true
after the load
event. 它将在load
事件之后将artist.visible字段值设置为true
。 This should work after some changes to the markup: 在对标记进行一些更改之后,这应该可以工作:
<div class="paintings" ng-show="artist.visible">
<a href="{{ artist.fields.link }}">
<img ng-src="{{ artist.fields.link }}" show-on-load /></a>
<h3> {{ artist.fields.title }} </h3>
</div>
You should use ng-init
instead. 您应该改为使用ng-init
。 Replace 更换
onload="showImageDiv(img{({$index})})"
with 与
ng-init="showImageDiv($index)"
And since you are using angular, make use of your controller
. 并且由于您使用的是角度,请使用您的controller
。 Inside your controller, write this: 在控制器内部,编写以下代码:
$scope.showImageDiv = function(index){
jQuery('#img'+index).show();
}
Update : 更新 :
You can also make use of ng-show
, instead of jQuery
: 您还可以使用ng-show
,而不是jQuery
:
<img src="{({ artist.fields.link })}" ng-init="showImageDiv($index)" ng-show="img[$index]" />
And in controller
: 并在controller
:
$scope.img=[];
$scope.showdiv = function(index){
$scope.img[index] = true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.