Anks
Anks

Reputation: 485

angular js directive to replace ng-src on img tag

Currently I have an image tag in which I need to do a JavaScript replace on. was looking online and I've read some peoples thoughts about using a directive to achieve this but haven't found an example that could help me.

My current setup looks like this:

HTML:

<img ng-src="{{day.Item.Logo}}" item-logo>

day.Item.Logo is just a string being returend that looks something like this.

http://domainnamehere.com/image%s%s.png

And my directive as it currently stands.

    myApp.directive("itemLogo", function() {
        return function(scope, element, attrs) {
           attrs.ngSrc = attrs.ngSrc.replace("%s", "24");
           attrs.ngSrc = attrs.ngSrc.replace("%s", "24");
        }
    });

I know I am obviously doing something wrong in the directive I believe but I dont know for sure. Essentially i'd like to replace both "%s" with "24" and return it back to the view before it makes the request to fetch/load the image.

Upvotes: 1

Views: 3252

Answers (1)

d_z
d_z

Reputation: 778

I think the problem is in order of directive processing by angular. When it compiles your directive, ng-src might already has been processed. I would modify the url in the controller just before putting it to the model.

Another way is to put a function call to ng-src which modifies the url.

ng-src='{{formatUrl(day.Item.Logo)}}'

Here is a JSBin

Upvotes: 2

Related Questions