我正在尝试创建我将在svg元素中使用的AngularJS指令.
该指令不创建svg元素,但使用存在的元素.我可以在开发工具中看到正确的svg标记,但浏览器不会显示它.
这是指令:
angular.module('ui.directives', []).directive('svgText',
function() {
return {
restrict: 'E',
replace: true,
template: '<text fill="green" x="4" y="20" font-weight="bolder" font-size="2" font-family="Arial">89</text>'
};
}
);
Run Code Online (Sandbox Code Playgroud)
发生这种情况是因为jQuery(AngularJS在引擎盖下使用)不知道如何创建svg元素.您可以通过向指令添加链接函数来解决此问题,该指令克隆已创建但在SVG名称空间中创建的元素.
一个可能更好的方法是将模板包装在SVG元素中(定义了命名空间),然后在link函数中拉出子元素并使用它,它已经在正确的命名空间中创建.
module.directive(
'svgText',
function () {
return {
restrict: 'E',
template: '<svg xmlns="http://www.w3.org/2000/svg"><text fill="green" x="4" y="20" font-weight="bolder" font-size="2" font-family="Arial">89</text></svg>',
replace: true,
link: function (scope, elem, attrs) {
// Extract the child element to replace the SVG element.
var child = angular.element(elem[0].firstElementChild);
// Copy attributes into element.
for (attrName in attrs) {
if(typeof attrs[attrName] === "string") {
child.attr(attrName, attrs[attrName]);
}
}
elem.replaceWith(child );
}
};
}
);
Run Code Online (Sandbox Code Playgroud)
我发表了一篇关于AngularJS + SVG的文章,讨论了很多这样的问题.
http://www.codeproject.com/Articles/709340/Implementing-a-Flowchart-with-SVG-and-AngularJS
| 归档时间: |
|
| 查看次数: |
2061 次 |
| 最近记录: |