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?

sil
  • 1,769
  • 1
  • 18
  • 34
  • Do you have any control over the backend? I.e. can you change what it returns? – Ed_ Mar 21 '14 at 10:25
  • 1
    possible duplicate of [AngularJS - Compiling dynamic HTML strings from database](http://stackoverflow.com/questions/18157305/angularjs-compiling-dynamic-html-strings-from-database) – sil Mar 21 '14 at 11:47
  • Ed: I can't change the backend. However, I believe I've now solved it, and marked this as a dup. – sil Mar 21 '14 at 11:49

0 Answers0