How to display image in AngularJS using ng-src directive

Waqas Anwar
12 February 2016
8586 Views

If you have an image url and you want to display it in html document using <img> element, you should use ng-src instead of src attribute to correctly bind the image url using AngularJS expression.

Using Angular markup like https://angularjs.org/img/{{vm.ImageFileName}} in a src attribute doesn't work right because the browser will try to fetch from the URL with the literal text until AngularJS replaces the expression inside {{vm.AbsoluteImageUrl}}. The ngSrc directive solves this problem.

AngularJS

(function () {
   'use strict';

   angular
      .module('app', [])
      .controller('DemoController', DemoController);

      function DemoController (){
         var vm = this;
         vm.AbsoluteImageUrl = "https://angularjs.org/img/AngularJS-large.png";
         vm.ImageFileName = "AngularJS-large.png";
      }
})();

HTML

<!DOCTYPE html>
<html lang="en-US">
<body ng-app="app">

<div ng-controller="DemoController as vm">
   <img alt="" ng-src="{{vm.AbsoluteImageUrl}}" />
   <img alt="" ng-src="https://angularjs.org/img/{{vm.ImageFileName}}" />
</div>

<script src="angular.min.js"></script>
<script src="app.js"></script>

</body>
</html>