我一直在使用以下代码隐藏我页面上任何'404'图像的'祖父母',并且效果很好:
function imgError(image){
image.parentNode.parentNode.style.display = 'none';
}
<img ng-src="{{photo.img}}" onerror="imgError(this);" id="image">
我想将此功能转移到自定义Angular指令中,以下是我当前的实现,但它不起作用。我认为我的问题在于错误地抓住图像的'祖父母'元素。
指令:
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>
答案 0 :(得分:2)
向我看来......并且在图片确认加载之前你不应该显示任何内容
<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
的主要元素的指令只会在图像加载后显示。范围变量最初将是未定义的,并使用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
答案 1 :(得分:1)
你应该在这里使用angular.element(this)
因为你已经使用链接函数的element
参数控制了元素,你应该使用jQLite .css
函数而不是使用JavaScript。
function link(scope, element, attrs) {
element.bind('error', function() {
element.parent().parent().css({'display': 'none'}); //you can pass that css from attribute
})
}
答案 2 :(得分:1)
hide-image="'display: none;'"
应该是
hide-image="display: none;"
(没有单引号)