AngularJS ng-href and svg xlink

You can use ng-attr-<some attribute>

ng-attr-xlink:href="{{xxx}}" works for me.


Note that you also need an empty xlink:href="" as initial value. – Derek Hsu


If, like me, you're looking for a way to add images to svg, you can do so adding:

xlink:href="" ng-href="{{ foo }}"

Example:

http://jsbin.com/sigoleya/1/edit?html,js,output

Where I found the solution:

https://github.com/angular/angular.js/issues/7697


I ran into a similar problem when trying to output a value for xlink:href that's tied to the model. Based on the user's chosen <option> in a <select> control, I was trying to show a dynamic SVG icon via the xlink:href attribute of the <use> element.

I found a thread about this in the GitHub Issues for AngularJS. Based on the discussion there, it appears that because a viable workaround exists, they've effectively tabled a fix by moving it to the Backlog milestone.

What ultimately worked for me was inspired by this JSBin:

http://jsbin.com/sigoleya/1/edit?html,js,output

Here's the code I used in my template:

<svg class="icon" data-ng-class="category.iconName">
  <use xlink:href="" data-ng-href="{{'#' + category.iconName}}">
</svg>

Given a category.iconName of icon-music, for example, Angular sets the xlink:href dynamically to #icon-music, which references the <svg id="icon-music"> element further up on the same page.

As others have noted, what's key is setting a blank xlink:href="" attribute on the element where you call the ngHref directive. Attribute order does not seem to matter. Using ng-attr-xlink:href="{{xxx}}" (as mentioned in Derek Hsu's answer) did not work for me.

All of this assumes Angular 1.3.36.