AngularJs Tutorial ng-src Directive

In this Tutorial we will learn following points :

    Use of ng-src directive.
    Using binding expression with the image src attribute.
    Why result using src attribute 404 error.

First we have to create image folder/directory inside our project and put any image like lusy.jpg.Now we will write code to call image and display in webpage.We will do hard code for display image inside html.

<html ng-app="myModule">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
</head>
<body>
	<div ng-controller="myController">
		<div>
			<img src="images/lusy.jpg" width="100" height="100"/>
		</div>
	</div> 
</body>
</html>

By using above script output will be:

sc_short

Now we will do image src path using databinding expression in angularjs dynamically.

code in script.js

//module
var myApp = angular.module("myModule", []);
//controller register with module
myApp.controller ("myController", function($scope) {
	var student =  {
			firstname : 'Lusy',
			student_pic : 'images/lusy.jpg'
			};
	$scope.student = student;
});

code in html.

<html ng-app="myModule">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<script src="script/script.js"></script>
</head>
<body>
	<div ng-controller="myController">
		<div>
			First Name : {{ student.firstname }}
		</div>
		<div>
			<img src="{{ student.student_pic }}" alt="{{ student.student_pic }}" width="100" height="100"/>
		</div>
	</div> 
	
</body>
</html>

Now output will be :

sc_short

Output on webpage is fine But because of these script :

<img src="{{ student.student_pic }}" alt="{{ student.student_pic }}" width="100" height="100"/>

we will get in console following error 404 not found image:

sc_short

For removing that 404 not found error modify in our code like below script with ng-src tag. If you will check your console then you will be found no error of 404.

<html ng-app="myModule">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<script src="script/script.js"></script>
</head>
<body>
	<div ng-controller="myController">
		<div>
			First Name : {{ student.firstname }}
		</div>
		<div>
			<img ng-src="{{ student.student_pic }}" alt="{{ student.student_pic }}" width="100" height="100"/>
		</div>
	</div> 
	
</body>
</html>

Using ng-src directive we can able to remove 404 not found error for image.