AngularJS - Display Default image if original image does not exists with example

By Hardik Savani | October 18, 2016 | Category : Javascript HTML jQuery Angular

We always require to check image is exists or not in given path, If not exists then we have to set default image. If we work on PHP or any framework then we check condition or something else for image exists of not to check But If you are working on AngularJS framework then we can do it using "directive".

AngularJS directive through we can simple check image is exists or not on the given url path. In this example i use ng-src and err-src attribute to manage image, directive will check ng-src url image is exists or not, if not then it will set err-src image as default.

So, I give you very basic example and you can simply understand how to use it, So let's see bellow example:


<!DOCTYPE html>



<title>AngularJS set ng src default image</title>

<script type="text/javascript" src="//"></script>

<script src=""></script>



<div ng-app="mainApp" ng-controller="myController" id="mainController">

<img ng-src="{{realImage}}" style="width:200px" err-src="{{ myDefaultImage }}">

<img ng-src="{{noImage}}" style="width:200px" err-src="{{ myDefaultImage }}">


<script type="text/javascript">

var app = angular.module("mainApp", []);

app.controller('myController', function($scope, $timeout) {

$scope.myDefaultImage = '';

$scope.realImage = '';

$scope.noImage = '';


app.directive('errSrc', function() {

return {

link: function(scope, element, attrs) {

element.bind('error', function() {

if (attrs.src != attrs.errSrc) {

attrs.$set('src', attrs.errSrc);



attrs.$observe('ngSrc', function(value) {

if (!value && attrs.errSrc) {

attrs.$set('src', attrs.errSrc);









Maybe it can help you...

Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.

We are Recommending you: