Preface
In daily development work, there are many requirements to display some pictures on a page. Sometimes, the address path of the image is set by the client's script (it may be retrieved from the database).
This is the era of Angularjs. When we want to use Angularjs to display images on pages, we will simply use: <img src=”path of image”>.
If we only consider the presentation, there is no doubt that it is OK, but a 404 (not found) error will be displayed in the browser's console.
To solve this problem, we need to use ng-Src . Before using ng-Src , I want to reproduce how this error occurs.
The sample code is as follows:
Sample source code
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> In the above example, there is an animal class that has three properties: Name , Color and Picture , and has been assigned values. Using the model binder, I used these properties on the page. For images, I used the <img> HTML tag.
Then run this example, the effect is as follows:
Then open the browser's console and you will see this error.
Unable to load resource: Server response status is 404 (Not Found).
So the question is, why does this error occur? How should it be solved?
Cause - When the DOM is parsed, it will try to get the picture from the server. At this time, the Angularjs binding expression {{ model }} on src attribute has not been executed yet, so an error of 404 not found occurred.
Solution- The solution version is: use ng-Src instead of src attribute in the picture. After using this directive, the request will only be issued after Angular executes this binding expression.
Examples of using ng-Src are as follows:
<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> Now that you open the browser's console again, it won't appear: 404 not found, this is because ng-Src is used.
definition
ng-Src- -This directive overrides src native attributes of the <img /> element.
Summarize
The above is the entire content of this article. I hope you like it. If you have any questions, you can leave a message to communicate.