4

I have the following image tag:

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

newImage 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 link 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 console.log(attrs) 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 ng-src 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 ng-src does it?

2
  • "I wonder how ng-src does it?" => you know that angularjs is open source ? You should really use ngSrc Commented Jun 4, 2014 at 14:57
  • @Bixi :) I know that. I went through it but could not understand it. Commented Jun 4, 2014 at 15:09

2 Answers 2

6

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!

Sign up to request clarification or add additional context in comments.

Comments

0

ng-src is nothing but another directive which passes a "source" attribute (or binds it) to a given directive / whatever.

So - what is the name of the directive you are trying to make? One option might be to encompass the entire <img.../> tag in your image-loader-directive

The other issue that might be occurring, could have to do with the fact that your DOM defines src="default.png" instead of something like src="{{ image_src }}". This way the minute your directive decides to change the meaning of image_src - the DOM will refresh and hence pull the correct image from its source.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.