flobacher / SVGInjector2

Fast, caching, dynamic inline SVG DOM injection library
MIT License
57 stars 8 forks source link

Angular Directive Fix #24

Open martyzz1 opened 7 years ago

martyzz1 commented 7 years ago

We had some issues with svg's who's data-src values were dynamic e.g. <svg data-src="{{$ctrl.path_to_svg""> The main issue is that the directive was updating prior to the digest cycle completing, and because there was no $watch setup to listen for subsequent changes....

Feel free to copy the function link function below into the main code, and for everybody else who wants to run the fix in the interim you can use the following decorator...

angular.module("app").config(['$provide', function($provide) {

        $provide.decorator("svgDirective", ['$delegate', 'svgInjectorFactory', '$timeout',
            function($delegate, svgInjectorFactory, $timeout) {
                var directive = $delegate[0];
                var cfg = svgInjectorFactory.getConfig();
                var link = function(scope, element, attrs) {
                    if (attrs["class"] && attrs["class"].indexOf(cfg.spriteClassIdName) >= 0) {
                        attrs.$observe("class", function() {
                            svgInjectorFactory.inject(element[0]);
                        });
                    } else if (attrs.dataSrc) {
                        $timeout(function() {
                            svgInjectorFactory.inject(element[0]);
                        });
                    } else if (attrs.src) {
                        $timeout(function() {
                            svgInjectorFactory.inject(element[0]);
                        });
                    }

                    scope.$watch('dataSrc', function(newVal, oldVal) {
                        if (oldVal !== newVal) {
                            console.log('dataSrc watch changed', element[0], newVal, oldVal);
                            svgInjectorFactory.inject(element[0]);
                        }
                    });
                };

                directive.compile = function() {
                    return function(scope, element, attrs) {
                        link.apply(this, arguments);
                    };
                };

                return $delegate;
            }]);
        }]);