在使用來自themoviedb.com的API時,我將用戶類型置於輸入字段中,並在每個鍵盤上發送API請求。在測試中,有時電影海報會是「空」而不是預期的海報路徑。我更喜歡默認使用佔位符圖片來表示未發現使用API請求的海報。當API返回空值時,如何更改AngularJS ng-src?
所以因爲整個poster_path網址不是由API提供的,由於我使用的是AngularJS NG重複,我已經構建像這樣(使用虛擬數據,以節省空間)的圖像標籤:
<img ng-src="{{'http://example.com/'+movie.poster_path}}" alt="">
但是,然後控制檯給我一個錯誤,因爲一個錯誤的請求,因爲完整的圖像路徑沒有返回。我嘗試使用OR提示:
{{'http://example.com/'+movie.poster_path || 'http://example.com/missing.jpg'}}
但是,在這種情況下不起作用。所以現在用javascript。我似乎無法通過使用getElementsByTagName或getElementByClass來獲取圖像源,並且使用getElementById似乎只抓取第一個重複,而沒有其他任何東西,我認爲是這種情況。但即使如此,我似乎無法取代圖像源。下面是代碼結構,我嘗試:
<input type="text" id="search">
<section ng-controller="movieSearch">
<article ng-repeat="movie in movies">
<img id="myImage" src="{{'http://example.com/'+movie.poster_path}}" alt="">
</article>
</section>
<script>
function movieSearch($scope, $http){
var string,
replaced,
imgSrc,
ext,
missing;
$(document).on('keyup', function(){
string = document.getElementById('search').value.toLowerCase();
replaced = string.replace(/\s+/g, '+');
$http.jsonp('http://example.com/query='+replaced+'&callback=JSON_CALLBACK').success(function(data) {
console.dir(data.results);
$scope.movies = data.results;
});
imgSrc = document.getElementById('myImage').src;
ext = imgSrc.split('.').pop();
missing='http://example.com/missing.jpg';
if(ext !== 'jpg'){
imgSrc = missing;
}
});
}
</script>
與我做錯了任何想法,或者什麼,我試圖甚至可以在全部完成?
使用指令在它的圖像預加載...如果預加載失敗,通過你的'missing'值SRC – charlietfl