Skip to content

Instantly share code, notes, and snippets.

@Bill77
Created October 22, 2015 17:54
Show Gist options
  • Save Bill77/05cde2352c54e0575404 to your computer and use it in GitHub Desktop.
Save Bill77/05cde2352c54e0575404 to your computer and use it in GitHub Desktop.
A conversion of (an older version of) svg4everybody to an angular directive. Since the functional testing was flaky, we decided to always embed the svg, thus the naming. :)
// Conversion of svg4Everybody into angular format by Bill Chen
// https://github.com/jonathantneal/svg4everybody
(function() {
'use strict';
angular.module('webApp')
.directive('use', svgEmbed);
svgEmbed.$inject = ['$http'];
function svgEmbed ($http) {
var directive = {
restrict: 'E',
link: link
};
return directive;
function link (scope, element, attrs) {
var svg = element.parent()[0];
var url = attrs.xlinkHref.split('#');
var url_root = url[0];
var url_hash = url[1];
if (url_root.length) {
$http.get(url_root, { cache: true }).success(function (data) {
var x = document.createElement('x');
x.innerHTML = data;
embed(svg, x.querySelector('#' + url_hash.replace(/(\W)/g, '\\$1')));
});
} else {
embed(svg, document.getElementById(url_hash));
}
element.remove();
}
function embed(svg, g) {
if (g) {
var viewBox = g.getAttribute('viewBox')
var fragment = document.createDocumentFragment()
var clone = g.cloneNode(true);
if (viewBox) {
svg.setAttribute('viewBox', viewBox);
}
while (clone.childNodes.length) {
fragment.appendChild(clone.childNodes[0]);
}
svg.appendChild(fragment);
}
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment