Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create AngularJs svg directive

I'm trying to create an angular (1.5.5) directive where the template is an svg element. I read this answer, and several others, but I'm not able to get my simple svg element to show. I have tried to simplify it as much as possible. So this simple directive should draw a circle when used inside a svg element, at least that is what I'm trying to achieve.

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>
        //`
    }
});

This does not show the circle with this html

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

if instead I change the directive to include the svg element, then it shows (since this is now an html element I assume)

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>

And it doesn't matter if I set the templateNamespace to "html" or "svg". It shows in either case.

Is it not possible to define an svg template in a directive, and instead I need to add it programmatically as suggested in this answer

What am I missing ?

Thanks

like image 298
Jesper Kristiansen Avatar asked Feb 01 '26 11:02

Jesper Kristiansen


1 Answers

Ahh - I found the problem, and I will post this as an answer instead of modifying my question, adding replace: true and the shape is shown

app.directive("svg01", () => {
    return {
        replace: true,
        templateNamespace: "svg",
        template: `
            <circle cx="50" cy="50" r="40" stroke="blue" stroke-width="4" fill="yellow" />
        `
like image 172
Jesper Kristiansen Avatar answered Feb 03 '26 07:02

Jesper Kristiansen