如果directive
产生img
,我试图写一个ng-src
来删除一个404
元素。该指令有效,但是断开的img
会显示一秒钟,然后将其删除。我正在尝试在GUI中呈现该元素之前将其删除。
TS:
import { IDirective } from "angular";
/* @ngInject */
export function imgSrcErr($http): ng.IDirective {
return {
link: (scope, element, attrs) => {
element.bind("error", () => {
element.parent().remove();
console.log("error");
});
}
};
}
HTML:
<img img-src-err ng-src="{{$ctrl.model.pictureUrl}}"/>
答案 0 :(得分:1)
您可能要考虑默认情况下隐藏图像(使用CSS或通过使用setAttribute('display', 'none')
直接操作元素),然后在成功加载后将其显示。
类似这样的东西:
imageElement.onload = function() {
imageElement.setAttribute('display', 'inline');
}
注意:在设置事件处理程序之前,该图像可能已经加载(例如,该图像是从缓存中加载的),在这种情况下,处理程序将不会触发。要解决此问题,您可以check to see if the image is already loaded,然后再附加事件处理程序。
答案 1 :(得分:0)
您可以采取一些解决方法,例如加载时将不透明度设置为0:
link: (scope, element, attrs) => {
element.addClass('opacity-0');
element.bind('error', () => {
element[0].remove(); // not sure why you remove parent of element, but up to you
});
element.bind('load', () => element.removeClass('opacity-1'));
}
opacity-0 {
opacity: 0;
}