Displaying dynamic SVG with AngularJS

Trying to generate an SVG based on data from the scope, but encountering issues with rendering - it comes out empty or displays 'NaN' for some unknown reason.

https://i.sstatic.net/vO70i.png

Additionally, errors are popping up right after the render process:

https://i.sstatic.net/Gw6HM.png

Is there a way to delay the rendering directive until the data is fully ready? Or could there be another underlying reason causing this issue?

The view for the directive appears as follows:

<svg height="500" width="500" ng-if="svgConfig.textConfig"> 
</g>
    <svg height="{{svgConfig.height}}" 
        width="{{svgConfig.width}}" 
        y="{{(svgConfig.textConfig.fontSize) + 1*svgConfig.textConfig.distance.Y}}">
        <g 
            transform="translate(0, {{svgConfig.textConfig.distance.Y}})">          
            <text font-family="{{svgConfig.textConfig.fontFamily}}" 
                font-size="{{svgConfig.textConfig.fontSize}}"
                x="0" y="0" 
                inline-size="200" 
                alignment-baseline="text-before-edge">
                {{line}}
            </text>     
        </g>
    </svg>
</g>

The directive structure is outlined below:

app.directive('myDirective', [ function() {
    return {
        restrict: 'E',
        templateUrl: './app/myDirective.html',
        controller: 'mySvgController',
        transclude: true
    };
}]);

And here's the related controller code:

modernFilterApp.controller('mySvgController', ['$scope', function($scope){
    $scope.init = function(){

        $scope.textFonts = textConfigEnum.data;

        // Container for svg settings
        $scope.svgConfig = {
            text:'',
            textConfig: {
                fontFamily: $filter('getTextConfigByType')(textConfigEnum.info.Arial).fontFamily,
                fontSize: 20,
                fontDecoration: null,
                fontWeight:null
            },
            distance:{
                X: 0,
                Y: 0
            }
        };
    };

    $scope.init();
}]);

Answer №1

The issue at hand is the incorrect usage of svgConfig.textConfig.distance.Y. The property distance does not belong to the textConfig object; instead, it is maintained as an individual property. This error is resulting in a calculation outputting a value of NaN. The correct reference should be svgConfig.distance.Y

I recommend utilizing the ng-attr-* attribute for dynamically rendering values of the x and y attributes, such as using ng-attr-y

</g>
    <svg height="{{svgConfig.height}}" 
        width="{{svgConfig.width}}" 
        ng-attrs-y="{{(svgConfig.fontSize) + 1*svgConfig.textConfig.distance.Y}}">
        <g 
            transform="translate(0, {{svgConfig.distance.Y}})">          
            <text font-family="{{svgConfig.textConfig.fontFamily}}" 
                font-size="{{svgConfig.textConfig.fontSize}}"
                x="0" y="0" 
                inline-size="200" 
                alignment-baseline="text-before-edge">
                {{line}}
            </text>     
        </g>
    </svg>
</g>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Run a PHP function using <button onclick=""> tag

Is it possible to trigger the execution of a PHP script when clicking an HTML button? I am aware that simply calling a PHP function directly from the button's onclick event like this: <button onclick="myPhpFunction("testString")">Button</butt ...

invoking a function at a designated interval

I am currently working on a mobile application built with Ionic and TypeScript. My goal is to continuously update the user's location every 10 minutes. My approach involves calling a function at regular intervals, like this: function updateUserLocat ...

How come I am getting the desired section from my split string only after running the function twice?

I've been working on a function that retrieves data from a form and sends it to a POST request, which in turn sends it to my MongoDB database. The following code snippet showcases the process of uploading an image to IPFS, extracting the IPFS hash fro ...

Error in MEAN Stack: Unable to access the property 'companyTitle' because it is undefined

I have established a MongoDB collection named joblist in my database. Additionally, I have developed a DB schema known as jobList.js. var mongoose = require('mongoose'); const joblistSchema = mongoose.Schema({ companyTitle: String, jobT ...

Utilizing a RESTful approach for ajax requests is effective, but there seems to be a

Trying to make an ajax call and facing some challenges. Used a REST test extension for Chrome called Postman [Link to it]. While the call works fine with the extension, encountering an "error 0" message when trying to send it through jQuery. The request s ...

Implementing JSON response in email functionality using Ajax and PHP

I've encountered a problem with my contact form. I'm receiving error messages for invalid email and incomplete fields, but I'm not getting a success message. As a result, the email is being sent twice without any confirmation message (I&apos ...

AngularJS directive element not displaying CSS styles properly

I've been grappling with this issue for the past few days and I just can't seem to crack it. Whenever I try adding a class to an AngularJS element directive, the styling appears in the code view of my browser (Chrome), but the styles themselves ...

Connect Angular Material by chaining together md-select elements from arrays and array of form inputs

I am encountering a challenge with combining chains in Angular Material. I aim to transition from this linked solution on jsfiddle to using md-select and md-option in Material. How should it function? It's quite simple. Here's the scenario: Se ...

What is the reason behind Chrome's automatic scrolling to ensure the clicked element is fully contained?

Recently, I have observed that when performing ajax page updates (specifically appends to a block, like in "Show more comments" scenarios) Chrome seems to automatically scroll in order to keep the clicked element in view. What is causing this behavior? Wh ...

The issue of Jquery selectors not functioning properly when used with variables

Currently working on a script in the console that aims to extract and display the user's chat nickname. Initially, we will attempt to achieve this by copying and pasting paths: We inspect the user's name in the Chrome console and copy its selec ...

The removal of a JQuery element can result in causing the webpage to become unresponsive and lead to

When attempting to create a loop in JQuery to remove elements from my HTML, I encountered an issue where the function caused my browser to hang and become unresponsive. Here is the JQuery code I used: function removeElement(){ var i =0; ...

The ng-click function is not functioning properly when combined with ng-bind-html within an ng-repeat loop

Currently, I am attempting to retrieve data using Jsonresult and Angularjs in MVC4. This is the Jsonresult function in the Controller: public JsonResult GetQuestionSets() { //... var selectedData = titles.Select(y => new { //... qsAction = y.q ...

Having issues retrieving a JSON array in PHP with the json_decode function

Can someone assist me with passing and returning an array to a PHP script? I have successfully tested the json_encode portion, but I am facing issues with the json_decode on the PHP side. Javascript scid_list = []; $('.filter_on').each ...

IE compatibility mode causing ckeditor dropdown to be hidden

When using the CKEditor editor bar inside a green div with another div below it, I noticed that when clicking on "font" or any other option that opens a dropdown menu, it gets hidden behind the bottom div. This issue seems to occur in browsers like Chrome ...

How can I display the console log output from JavaScript on an HTML webpage?

If I have a JavaScript function that logs its output in the console using console.log(), is there a way to then export that result into the HTML console? Appreciate any advice on this. ...

Utilize jQuery to transform array values into date objects

I am receiving an array from a .net controller. The values I am getting for dates are: /Date(1445256000000)/ and /Date(1445256900000)/ Instead of this, I need to convert these into proper date values. Now that I have an array of objects, I want to upda ...

Developing a concealed Repeater element that is retained in the source code for utilization in JavaScript tasks

I am currently working on a setup with two repeaters: one that is displayed when the page first loads, and another that I want to keep hidden until a link called "Add Stuff" is clicked. My goal is to use JavaScript to make this second repeater visible upon ...

What is preventing Safari and Firefox from properly handling audio data from MediaElementSource?

It appears that neither Safari nor Firefox can process audio data from a MediaElementSource with the Web Audio API. var audioContext, audioProcess, audioSource, response = document.createElement('h3'), display = document.createElement( ...

Creating a Timeless Banner with the Magic of `background:url()`

I have a banner placed within a div tag that displays my banner image. I am trying to create a fading effect when transitioning to the next image, but I am struggling to achieve this. I attempted to use jQuery fadeIn(), however, it did not work as expected ...

Exporting a function from one module does not automatically make it accessible in another module

I'm stuck trying to call the retrieve_endpoints function from cli_config.js. I made sure to add the functions to the module exports and included the require statement in the cli_config file. But for some reason, I can't seem to access the retriev ...