我正在阅读包含图片路径的文件。此图像路径可能是空的或错误的。因此,如果出现错误,我想用字符串替换图像,而不是用其他图像替换。 我使用了一个小技巧,但我想知道它是否正确或有更好的方法。
这是HTML / Angular代码的片段:
<h1><img ng-src="{{component.img || 'none'}}" err-src><span>{{component.title}}</span></h1>
这是我创建的指令:
myApp.directive('errSrc', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('error', function() {
element.parent().addClass("no-image");
});
}
};
});
最初,img是可见的,而span则不是。当然在CSS文件中我创建了一个类h1.no-image,它将显示跨度并隐藏img。
有没有人知道更好的方式,或者更多的Angular&#34;式方式来实现这个功能?感谢
答案 0 :(得分:2)
ng-src="{{component.img || '//:0'}}"
答案 1 :(得分:0)
尝试以下行:
<img ng-src="(component.img === undefined) ? 'none' : component.img" err-src>
答案 2 :(得分:0)
您可以使用2个img
代码:
<img ng-src="{{url}}" ng-if="url_correct"/>
<img src="url_to_default_picture" ng-if="!url_correct"/>
因此ng-if
只会在结果html中插入一个标记