How to Display Default image if original image does not exists in AngularJS ?

Today now in this post i will show you How to Display Default image if original image does not exists in AngularJS ? Sometimes we may need to check the image is exists or not in the given path. If image is not exists then we need to set a default image. If you are work on any PHP or any framework then you check give a condition or something else for checking image is exists not to . But If we are working on any AngularJS project then we can do it by using “directive”.

By using AngularJS directive we can easily check the image is exists or not on the given url path. So now In this example i will use ng-src and err-src attribute for manage the image, directive will check with ng-src url image is exists or not, if not found then it will set back err-src image as default.

So, here I will give you a very basic example and we can simply understand this how to use it.

So let’s see the 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);

Read Also: How to implement infinite ajax scroll pagination in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook


About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →