How to access src attribute in Angular directive when using ng-src

I have the following HTML (inside gsp):

<img ng-src="${resource(dir: '')}/images/stores/closeBTN.svg" />

      

I want to use Modernizr to determine if SVG is supported or not, and switch the image to png if it is not. I adapted this directive: https://github.com/tinacious/angular-svg-png

angular.module('svgPng', [])
  .directive('img', function () {
    return {
      restrict: 'E',
      link: function (scope, elem, attrs) {
        if ( typeof Modernizr !== 'undefined' && !Modernizr.svg ) {
          elem.attr('src', attrs.src.replace('.svg', '.png'));
        }
      }
    };
  });

      

The problem is attrs.src is undefined, so the replacement doesn't work. I know ng-src is supposed to populate the src, so I need to force a digest loop or do something to determine the src?

+3


source to share


1 answer


You do this too early before the digest loop, which processes ng-src

and adds the src attribute. So give the loop to the digest, you can verify this by putting it in $timeout

or using setTimeout

.

 .directive('img', function () {
    return {
      restrict: 'E',
      link: function (scope, elem, attrs) {
        if ( typeof Modernizr !== 'undefined' && !Modernizr.svg ) {
         $timeout(function(){
            elem.attr('src', attrs.src.replace('.svg', '.png'));
         }, false);
        }
      }
    };
  });

      



Or is it better to make the replacement too early before it ngSrc

can even handle it. Use the compile function to replace the extension in the ng-src attribute value, and this will also prevent images from being loaded as it would have been in the previous case (one with .svg and one with .png).

 .directive('img', function () {
        return {
          restrict: 'E',
          compile: function (elem, attrs) {
            if ( typeof Modernizr !== 'undefined' && !Modernizr.svg ) {
               attrs.$set('ngSrc', attrs.ngSrc.replace('.svg', '.png'));
            }
          }
      };
 });

      

+2


source







All Articles