2015-09-22 26 views
1

我在一個圖像標籤中有一個ng-src屬性,它是從指令的模板屬性中加載的,該屬性應該加載用戶選擇的圖像。然而,當頁面加載時,控制檯輸出一個404,因爲沒有選擇圖像,並且ng-src正在加載一個空圖像。我現在有這是在指令模板字符串內部的字符串串聯有效的ng-src語法字符串

"<img ng-src="myserver.com/{{imagesPath+ selectedImage}}"></img>" 

但每當selectedImage是一個空字符串,我得到空的請求。

我試圖將其更改爲是

"<img class='snapshot' ng-src='{{selectedImage.length? \'myserver.com\' + imagesPath +selectedImage : \'\' }}'></img>" 

這是行不通的。什麼是正確的語法?

回答

0

您應該檢查selectedImage.length> 0,所以每當有選擇的圖像發現,它會創建一個src路徑

"<img class='snapshot' ng-src='{{selectedImage.length> 0 ? \'myserver.com\' + imagesPath +selectedImage : \'\' }}'/>" 

更好的方式是隱藏從HTML標籤img時沒有圖像使用ng-if指令。

"<img ng-if="selectedImage.length > 0" ng-src="myserver.com/{{imagesPath+ selectedImage}}"/>" 
+0

@Alan有幫助嗎? –

5

我有同樣的問題,使用ng-if解決了它(謝謝你!!)。雖然我不得不改變字符串在ng-src中的連接方式:

ng-src="{{'myserver.com/'+ imagesPath}}"