AngularJS ng-href and svg xlink

Leon Radley picture Leon Radley · Apr 9, 2013 · Viewed 17.7k times · Source

I'd like some input on using xml namespaced attributes with angular.

The problem is angular comes with a couple of directives to handle writing attributes such as href and src when angular has parsed the expresssions (otherwise the browser will try to load {{mymodel.myimage}} as a url)

https://github.com/angular/angular.js/blob/master/src/ng/directive/booleanAttrs.js#L329

The problem I'm facing is that I'm using angular to output svg together with D3 and since angular doesn't have a way to output xlink:href I was stuck.

I created a custom directive that outputs xlink:href

app.directive('ngXlinkHref', function () {
  return {
    priority: 99,
    restrict: 'A',
    link: function (scope, element, attr) {
      var attrName = 'xlink:href';
      attr.$observe('ngXlinkHref', function (value) {
        if (!value)
          return;

        attr.$set(attrName, value);
      });
    }
  };
});

Full demo: http://plnkr.co/edit/cMhGRh

But it seems that if I don't manually add xlink:href to the element, the svg image will not render.

Any suggestions on how to best handle xml namespaces / svg together with angular would be greatly appreciated.

Answer

Derek Hsu picture Derek Hsu · Sep 1, 2014

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