angular .module('ma-directives') .directive('maSvgIcon', maSvgIconDirective);
function maSvgIconDirective($http, $templateCache) { return { restrict: 'E', replace: false, scope: { src: '@' }, link: function (scope, element, attr) { // Use either pre-configured SVG or URL source, respectively. attr.$observe('src', function (attrVal) { element.empty(); if (attrVal) { loadIcon(attrVal).then(function (svg) { element.html(svg); applyStyles(element.children()[0]); }); } }); } };
function loadIcon(url) { return $http.get(url, { cache: $templateCache }).then(function (result) { return result.data; }); }
function applyStyles(element) { var viewBoxSize = 24; angular.forEach({ 'fit': '', 'height': '100%', 'width': '100%', 'preserveAspectRatio': 'xMidYMid meet', 'viewBox': element.getAttribute('viewBox') || ('0 0 ' + viewBoxSize + ' ' + viewBoxSize) }, function (val, attr) { element.setAttribute(attr, val); }, this); angular.forEach({ 'pointer-events': 'none', 'display': 'block' }, function (val, style) { element.style[style] = val; }, this); } }