Mudits
Mudits

Reputation: 1633

On updating an image url the image doesn't get rendered on frontend

I have written a directive that renders screenshot of a page, if a screenshot is available else it shows a placeholder.

commonDirectives.directive("showScreenShot", function () {
return {
    restrict: 'A',
    replace: true,
    scope:{},
    link: function(scope, element, attrs){
        var template = '';
        if(attrs.url){
            template += '<div><img src=' + attrs.url + '></div>';
        }
        else{
            template += '<div class="placeholder"></div>'
        }
        element.replaceWith(template)
    }
}
})

It is able to render the image properly the first time but the second time rendering fails. It is unable to show the image. I don't understand why it is unable to render image even though the image url points to right image.

UPDATE

What if I want to do something like re-render an image after a timewait of say 10 secs, I can't use $watch because the URl remains the same, but the image at the given url gets updated after 10 secs:

commonDirectives.directive("showScreenShot",['$timeout', function ($timeout) {
return {
    restrict: 'A',
    replace: true,
    scope:{
        url: '@'
    },
    template: '<div ng-if="!url" class="dbimg placeholder">' +
    '<div class="phicons">' +
    '   <i class="phicn icon2-bars-3 p1"></i>' +
    '   <i class="phicn icon2-stats p2"></i>' +
    '   <i class="phicn icon2-graph p3"></i>' +
    '   <i class="phicn fa fa-table p4"></i>' +
    '</div>' +
    '</div>',
    link: function(scope, ele, attrs) {
        var template;
        if(attrs.url){
            template = '<div class="snapshotmsg">Generating preview ...</div><div class="dbimg placeholder">';
            $timeout(function () {
                template = '<div class="db_img"><img ng-src="' + attrs.url + '"></div>'
                ele.replaceWith(template)
            }, 10000);
            ele.replaceWith(template)
        }
    }
}

}]);

Upvotes: 0

Views: 224

Answers (2)

New Dev
New Dev

Reputation: 49590

When the link function runs (when the directive is first compiled), the template that you generate is added to the DOM. Later, when you change the url attribute there is nothing that triggers a change in the DOM.

The easiest way to go would be to use an isolate scope property of url rather than an attribute. You won't even need a link function if you just template your directive smartly by re-using built-in directives.

.directive("showScreenShot", function () {
  return {
    restrict: 'A',
    scope:{
       url: "@"
    },
    template: '<div ng-if="url"><img ng-src="{{url}}"/></div>' + 
              '<div ng-if="!url" class="placeholder"></div>'
  }
})

Upvotes: 1

squiroid
squiroid

Reputation: 14027

Use :- ng-src

 template += '<div><img ng-src=' + attrs.url + '></div>';

Upvotes: 1

Related Questions