0

In my angular app, I get handed a bunch of HTML from a backend API. That HTML contains things like this: <p><img data-is-gallery="true" id="img0001" src=""></p>

Elsewhere in the API response I have a list of image URLs by ID. I currently write the HTML into the page by setting $scope.data to the API response in my controller, and then

<div ng-repeat="block in data.htmlblocks">
  <div ng-bind-html="block.content"></div>
</div>

in my partial.

The API response looks, roughly, like this:

{ htmlblocks: [
    { content: '<p><img data-is-gallery="true" id="img0001" src=""></p>' }
  ], images: {
    img0001: { src: "http://example.com/img1.png" }
  }
}

What I want to happen is that I can also update the <img> elements within an html block; that is, I want to fill in the src attribute on the <img> element by looking up the <img id> in the images section of the API response. So the partial writes out the HTML block from the API, and then the src attribute of that <img> is updated so that it ends up being <img data-is-gallery="true" id="img0001" src="http://example.com/img1.png">.

I thought the way to do this was with a directive:

.directive("isGallery", function() { 
    return { 
        link: function(scope, element, attrs) {
            // do something relevant with element here
        }
    } 
});

that is, when the partial wrote out the html blocks, the directive would get called because I'm writing HTML with <img data-is-gallery> and I have an isGallery directive.

However, this doesn't work; the link function isn't ever called.

Am I going about this completely the wrong way?

3
  • Do you have any control over the backend? I.e. can you change what it returns? Commented Mar 21, 2014 at 10:25
  • 1
    possible duplicate of AngularJS - Compiling dynamic HTML strings from database Commented Mar 21, 2014 at 11:47
  • Ed: I can't change the backend. However, I believe I've now solved it, and marked this as a dup. Commented Mar 21, 2014 at 11:49

0

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.