gpt4 book ai didi

javascript - 隐藏元素 'grandparent' 的 Angular 指令

转载 作者:行者123 更新时间:2023-11-29 18:07:45 25 4
gpt4 key购买 nike

我一直在使用以下代码来隐藏我页面上任何“404”图像的“祖 parent ”,并且效果很好:

function imgError(image){
image.parentNode.parentNode.style.display = 'none';
}

<img ng-src="{{photo.img}}" onerror="imgError(this);" id="image">

我想将此功能移动到自定义 Angular 指令中,下面是我当前的实现,但它不起作用。我认为我的问题在于错误地捕获了图像的“祖 parent ”元素。

指令:

angular
.module('app')
.directive('hideImage', hideImage);

function hideImage() {
var directive = {
link: link,
restrict: 'A'
};
return directive;

function link(scope, element, attrs) {
element.bind('error', function() {
angular.element(this).parent().parent().attr('style', attrs.hideImage);
})
}
}

HTML:

<div ng-repeat="photo in event.photos">
<a ng-href="{{photo.link}}" target="_blank" title="{{photo.text}}">
<img ng-src="{{photo.img}}" hide-image="'display: none;'" id="image">
</a>
</div>

最佳答案

对我来说似乎倒退了......并且在确认加载图像之前你不应该显示任何东西

<div ng-repeat="photo in event.photos" image-wrapper ng-show="imageLoaded">
<a ng-href="{{photo.link}}">
<img ng-src="{{photo.img}}">
</a>
</div>

主元素上的指令现在使用 ng-show,它只会在图像加载发生后显示。 scope 变量最初是未定义的,并使用图像的 onload 事件将其设置为 true

angular
.module('app')
.directive('imageWrapper', imageLoader);

function imageLoader() {
var directive = {
link: link,
restrict: 'A'
};
return directive;

function link(scope, element, attrs) {
element.find('img')[0].onload=function(){
scope.$apply(function(){ // use $apply for all events outside of angular
scope.imageLoaded=true;
})
})
}
}

另请注意,您不能在页面中重复 ID

关于javascript - 隐藏元素 'grandparent' 的 Angular 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30017784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com