How to display image in AngularJS using ng-src directive

Waqas Anwar
12 February 2016

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{{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.


(function () {
   'use strict';

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

      function DemoController (){
         var vm = this;
         vm.AbsoluteImageUrl = "";
         vm.ImageFileName = "AngularJS-large.png";


<!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="{{vm.ImageFileName}}" />

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