Showing image only when fully loaded (Angular 1)

While working for a client, a requirement came up requesting for images only to be visible when fully downloaded.

The reason for this is that currently the images would load line by line which doesn't look quite nice. 

I started playing around a little but nothing worked as I would have liked, so I had to go deeper.


Directives to the rescue!

I ended up creating a new directive and hooked it up in my markup.

angular.module('app', [])
.directive("dynamicImage", function () {
  return {
    restrict: 'E', //restrict only to elements
      scope: {
        imageSource: '=src' //hook up to the outside scope
      template: '<img ng-show="showImage" src="{{ imageSource }}">',
      //get the element and bind to the load event
      link: function ($scope, iElm, iAttrs, controller) {
        $scope.showImage = false;
        iElm.find('img').bind('load', function (e) {
        //when loaded show the image            
        $scope.$apply('showImage = true');

//keep in mind that you don't need interpolation here
//so pass only the property without the '{{}}'
<dynamic-image src="propertyHoldingTheImageSource"></dynamic-image>

If you try it out now you won't see the image until fully loaded. 

To enhance the user experience a little more you can add a background image to the parent <div> which can serve as a placeholder but this is a topic for another time :)

Until then, happy coding!