callmekatootie callmekatootie - 14 days ago 6x
AngularJS Question

How to change image source attribute through directive

I have the following image tag:

<img src="default.png" data-new-image/>

is a directive that I have defined that will fetch the image from the server (based on some criteria) and while it calculates and fetches the image, I have the default.png image file shown.

In this directive, I have defined the
function as:

return {
link: function (scope, element, attrs) {
//My custom logic here to determine which image to show
//and then fetch from the server
//After HTTP request, assigning image to image source
attrs.src = "image_fetched_from_server.png";

But this does not update the images src attribute. I can see the image fetched clearly and a
after assigning the image shows that the source attribute was updated with new image. But the DOM inspector in the browser shows no change to the source - it still shows default.png

I am using directive here and not controller - I understand I can use controller and use
but I have this logic across multiple controllers and a directive is the best option I have. How do I change the source of the image tag? I wonder how
does it?


I found the cause.

To set values in the attribute, I needed to use attrs.$set(attribute_name, value).

Thus, I replaced attrs.src with attrs.$set('src', 'image_fetched_from_server.png'); and it worked!