前言
在日常開發工作中,有很多需求是在一個頁面上顯示一些圖片。有時,圖片的地址路徑是由客戶端的腳本來設置(它有可能是從數據庫中獲取的)。
這是Angularjs的時代,當我們想使用Angularjs來實現在頁面中展示圖片,我們會簡單使用: <img src=”path of image”>.
如果我們只考慮展示,毫無疑問它沒問題,但是在瀏覽器的控制台中會顯示一個404 (not found) 錯誤。
為了解決這個問題,我們需要使用ng-Src 。在使用ng-Src之前,我想給你重現一下這個錯誤是如何產生的
示例代碼如下:
示例源碼
Script.js
var testApp = angular .module("testModule", []) .controller("testController", function ($scope) { var animal = { name: "CAT", color: "White", picture: "/images/cat.jpg", }; $scope.animal = animal; });Index.html
<html ng-app="testModule"> <head> <title></title> <script src="scripts/angular.min.js"></script> <script src="scripts/js/script.js"></script> </head> <body> <div ng-controller="testController"> Name: {{animal.name}} <br /> Color: {{animal.color}} <br /> <img src="{{animal.picture}}" /> </div> </body> </html>在上述例子中,有一個animal類,它擁有三個屬性: Name , Color和Picture ,且已經賦值了。使用模型綁定器,在頁面上我使用了這些屬性。 對於圖片,我使用了<img> HTML標籤。
然後運行這個示例,效果如下:
然後打開瀏覽器的控制台,就會看到這個錯誤。
無法加載資源:服務器響應狀態為404 (Not Found)。
那麼問題來了,為什麼會出現這個錯誤?應該如何解決?
原因-當DOM 被解析時,會嘗試從服務器獲取圖片。 這時, src屬性上的Angularjs 綁定表達式{{ model }}還沒有執行,所以就出現了404 未找到的錯誤。
解決方案-解決的版本就是:在圖片中使用ng-Src代替src屬性,使用這個指令後,請求就只會在Angular執行這個綁定表達式之後才會發出。
使用ng-Src的示例如下:
<html ng-app="testModule"> <head> <title></title> <script src="scripts/angular.min.js"></script> <script src="scripts/js/script.js"></script> </head> <body> <div ng-controller="testController"> Name: {{animal.name}} <br /> Color: {{animal.color}} <br /> <img ng-src="{{animal.picture}}" /> </div> </body> </html>現在你再打開瀏覽器的控制台,就不會出現:404 未找到, 這是因為使用了ng-Src 。
定義
ng-Src-這個指令覆蓋了<img />元素的src原生屬性。
總結
以上就是這篇文章的全部內容,希望大家能夠喜歡,如果有疑問可以留言交流。