我<img>
:定義默認的圖像,如果變量{{圖像}}爲空
<img width="90" height="90" src="{{image}}" />
默認圖像文件夾:assets/img/pic_user.png
我如何定義未在變量定義的默認圖像:{{image}}
?
我<img>
:定義默認的圖像,如果變量{{圖像}}爲空
<img width="90" height="90" src="{{image}}" />
默認圖像文件夾:assets/img/pic_user.png
我如何定義未在變量定義的默認圖像:{{image}}
?
使用邏輯OR操作||
<img width="90" height="90" src="{{image||'assets/img/pic_user.png'}}" />
你可以存儲默認圖像路線變量,然後使用三元運算符的情況下使用該image
不存在:
defaultImage: string = "assets/img/pic_user.png";
然後在你的模板:
<img width="90" height="90" [src]="image ? image : defaultImage" />
請注意,我用屬性綁定而不是插值,在我看來,它更優雅。
有一招在JavaScript中設置默認值:
var a = newValue || 0;
同樣也適用於角。 你的情況:
<img width="90" height="90" src="{{image || 'assets/img/pic_user.png' }}" />
使用備用圖片
<img fallback-src="fallbackimg" ng-src="{{image}}"/>
myApp.directive('fallbackSrc', function() {
var fallbackSrc = {
link: function postLink(scope, iElement, iAttrs) {
iElement.bind('error', function() {
angular.element(this).attr("src", iAttrs.fallbackSrc);
});
}
}
return fallbackSrc;
});
真棒!謝謝 :) – Santosh