How to display default image if image not available using AngularJs

In this article I am going to explain how to display default image if image not available or uploaded using AngularJs.





Description:
I am displaying the user’s detail (Name, Email with profile pic) in Grid. I want to show by default image (Image not available) if users didn’t upload their image or image is missing.

Implementation:

We can do this using conditional logic as shown below:

<img ng-src="{{users.src || 'images/img-not-available.png'}}" alt="" title="{{emp.Name}}" width="150" height="150" />


Example:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AngularJs Tutorial</title>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
  <style>
  table tr td
  {
         padding: 5px 30px 0 0;
  }
  a
  {
          color: #E91E63;
          font-weight:bold;
          text-decoration:none;
  }
  </style>
<script>
    var bookApp = angular.module("testapp", []);
    bookApp.controller('testController', function ($scope) {
        $scope.userList = [
            { "Name": "John", "Email": "John@gmail.com", "src": "images/image.jpg" },
            { "Name": "Vinod", "Email": "Vinod@yahoo.com", "src": "images/img1.jpg"},
            { "Name": "Steve", "Email": "Steve@hotmail.com", "src": "images/img2.jpg" },
            { "Name": "Dan", "Email": "Dan@rock.com", "src": "" },
            { "Name": "Jonshan", "Email": "", "src": "images/img3.jpg"},
            { "Name": "Rocky", "Email": "Rocky@rocks.com", "src": "images/pic.jpg" },
            { "Name": "Santhom", "Email": "", "src": "" }
            ];
    });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <fieldset style="width:40%">
    <legend>AngularJs Tutorial</legend>
    <div ng-app="testapp" ng-controller="testController">
  
    <table>
    <tr>
    <td>Search :</td>
    <td colspan="3"><input type="text" placeholder="Search" ng-model="name"></td>
    </tr>
    <tr>
    <td></td>
    <td colspan="2"></td>
    </tr>
    </table>
    <table>
    <tr>
    <td>S.No.</td>
    <td><a href="" ng-click="sortType='Name';reverse=!reverse">Name</a></td>
    <td><a href="" ng-click="sortType='Email';reverse=!reverse">Email</a></td>
    <td></td>
    </tr>
     <tr ng-repeat="users in userList|orderBy:sortType:reverse|filter:name">
    <td>{{$index+1}}</td>
    <td>{{users.Name}}</td>
    <td>{{users.Email || 'Email Not Available'}}</td>
    <td><img ng-src="{{users.src || 'images/img-not-available.png'}}" alt="" title="{{emp.Name}}" width="150" height="150" /></td>
    </tr>
    </table>
    </div>
    </fieldset>   
    </form>
</body>
</html>




Post a Comment

0 Comments