Detailed description of the use of ng-src commands in AngularJS, angularjsng-src
Preface
In daily development, there are many requirements for displaying images on a page. Sometimes, the image address path is set by the client script (it may be obtained from the database ).
This is the era of Angularjs. When we want to use Angularjs to display images on the page, we will simply use:.
If we only want to display it, there is no doubt it is okay, but a 404 (not found) error will be displayed in the browser console.
To solve this problem, we need to useng-Src
. In useng-Src
Before that, I want to reproduce how this error was generated.
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
In the preceding exampleanimal
Class, which has three attributes:Name
,Color
AndPicture
And has been assigned a value. Using the model binder, I use these attributes on the page. For images, I used
HTML Tag.
Then run this example. The effect is as follows:
Then open the browser console and you will see this error.
Unable to load resources: the server response status is 404 (Not Found ).
So the question is, why is this error? What should we do?
Cause-When the DOM is parsed, it will try to get the image from the server. At this time,src
Angularjs binding expression on the property {{ model }}
The Error 404 was not found.
Solution-The solution version is: Used in the imageng-Src
Replacesrc
Attribute. After this command is used, the request will only be sent after Angular executes the binding expression.
An example of using ng-Src is as follows:
Now you can open the console of the browser and it will not appear: 404 Not found. This is becauseng-Src
.
Definition
ng-Src-
This command overwrites
Elementsrc
Native attributes.
Summary
The above is all the content of this article. I hope you will like it. If you have any questions, you can leave a message.