javascript - AngularJS 无法正确渲染 SVG

标签 javascript angularjs svg

我有一个指令,应该将 SVG 元素附加到指令元素

.directive('aSvg', function ($compile) {
    return {
        restrict: 'E',
        replace: true,
        link: function (scope, element, attrs) {
            var svgTag = angular.element('<svg viewBox="0 0 4000 2000" version="1.1"><defs><marker id="StartMarker" viewBox="0 0 12 12" refX="12" refY="6" markerWidth="3" markerHeight="3" stroke="green" stroke-width="2" fill="none" orient="auto"><circle cx="6" cy="6" r="5"></circle></marker><marker id="MidMarker" viewBox="0 0 10 10" refX="5" refY="5" markerUnits="strokeWidth" markerWidth="3" markerHeight="3" stroke="lightblue" stroke-width="2" fill="none" orient="auto"><path d="M 0 0 L 10 10 M 0 10 L 10 0"></path></marker><marker id="EndMarker" viewBox="0 0 10 10" refX="5" refY="5" markerUnits="strokeWidth" markerWidth="3" markerHeight="3" stroke="red" stroke-width="2" fill="none"><rect x="0" y="0" width="10" height="10"></rect></marker></defs><path d="M 200 250 L 700 100 L 900 350 L 1200 400 L 1300 200 L 1700 680 L 2200 680 L 2600 400" fill="none" stroke="black" stroke-width="50" marker-start="url(#StartMarker)" marker-mid="url(#MidMarker)" marker-end="url(#EndMarker)"></path><path d="M 1000 750 S 2000 750 2500 1250 S 1200 1000 1300 1400 S 1700 1480 1900 1200" fill="none" stroke="tomato" stroke-width="50" marker-start="url(#StartMarker)" marker-mid="url(#MidMarker)" marker-end="url(#EndMarker)"></path></svg>');
            $compile(svgTag)(scope);
            angular.element(svtTag).appendTo(element[0]);
        }
    };
});

在 html 中,我将指令作为元素:

<body>
    <div>
        <a-svg></a-svg>
    </div>
</body>

但是,SVG 渲染不正确,仅显示 2 条线(黑色和橙色),但没有渲染任何标记。示例中使用的 SVG 似乎是正确的,因为如果我将其保存到文件中,它会正确呈现,但由于某种原因,它无法在 AngularJS 中工作。

我在这里缺少什么?

提前致谢。

编辑1:我使用的是AngularJS v1.2.20,我尝试使用v1.3.0,但仍然有同样的问题。

最佳答案

经过更多研究,我发现问题出在 Angular 路由中,更具体地说是在 <base href='/'> 中。标签与 SVG 标记中定义的链接混淆。

我通过更改每个路径的标记属性中的 url 解决了我的问题(请注意 marker-startmarker-midmarker-end 属性中的 /myroute ):

<path d="M 200 250 L 700 100 L 900 350 L 1200 400 L 1300 200 L 1700 680 L 2200 680 L 2600 400" fill="none" stroke="black" stroke-width="50" marker-start="url(/myroute#StartMarker)" marker-mid="url(/myroute#MidMarker)" marker-end="url(/myroute#EndMarker)"></path>

有关更多详细信息,我建议阅读问题 here 已接受的答案.

关于javascript - AngularJS 无法正确渲染 SVG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26626662/

相关文章:

javascript - 将 $(this) 传递给函数

javascript - 如何禁用页面中的每次点击,仅在输入文本中自动对焦?

javascript - Angular : Why is this not working? 中的包含和范围

javascript - 如何在 HTML 中加倍缓冲 svg

javascript - 在循环中将传入的值设置为事件监听器不起作用

javascript - 多元素选择器上的 jQuery 方法链接

javascript - Angular 2 - 带有输入文件的模型驱动表单(文件上传)

javascript - AngularJS,如何在 ng-if 变化时触发与 dom 相关的 javascript

svg - 此 SVG 无效。在打开之前验证它

php - 从客户端 DOM 序列化 SVG 的最佳方式是什么?