【问题标题】:how to create AngularJs svg directive如何创建 AngularJs svg 指令
【发布时间】:2016-08-16 12:21:55
【问题描述】:

我正在尝试创建一个 Angular (1.5.5) 指令,其中模板是一个 svg 元素。我读了这个answer 和其他几个,但我无法显示我的简单 svg 元素。 我试图尽可能地简化它。所以这个简单的指令在 svg 元素中使用时应该画一个圆圈,至少这是我想要实现的。

app.directive("svg01", () => {
    return {
        templateNamespace: "svg",
        template: `
            <circle cx="50" cy="50" r="40" stroke="blue" stroke-width="4" fill="green" />
        `
        //template: `
        //  <svg width="100" height="100">
        //      <circle cx="50" cy="50" r="40" stroke="blue" stroke-width="4" fill="white" />
        //  </svg>
        //`
    }
});

这不会显示带有这个 html 的圆圈

<div style="height: 100px; background-color: lightgreen">
    <svg width="100" height="100">
        <svg01></svg01>
    </svg>
</div>

如果我改为更改指令以包含 svg 元素,那么它会显示(因为我现在假设这是一个 html 元素)

app.directive("svg01", () => {
    return {
        templateNamespace: "svg",
        //template: `
        //  <circle cx="50" cy="50" r="40" stroke="blue" stroke-width="4" fill="green" />
        //`
        template: `
            <svg width="100" height="100">
                <circle cx="50" cy="50" r="40" stroke="blue" stroke-width="4" fill="white" />
            </svg>
        `
    }
});

<div style="height: 100px; background-color: lightgreen">
    <svg01></svg01>
</div>

我将 templateNamespace 设置为“html”还是“svg”都没关系。它显示在任何一种情况下。

是否无法在指令中定义 svg 模板,而是需要按照this answer 中的建议以编程方式添加它

我错过了什么?

谢谢

【问题讨论】:

    标签: angularjs svg angularjs-directive


    【解决方案1】:

    啊-我发现了问题,我将把它作为答案发布,而不是修改我的问题,添加 replace: true 并显示形状

    app.directive("svg01", () => {
        return {
            replace: true,
            templateNamespace: "svg",
            template: `
                <circle cx="50" cy="50" r="40" stroke="blue" stroke-width="4" fill="yellow" />
            `
    

    【讨论】:

      猜你喜欢
      • 2013-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      相关资源
      最近更新 更多