A guide to creating a JavaScript function that outputs a script in string form

Currently, I am utilizing angular and seeking to add a script to my directive's template. My goal is to create a function that can take the necessary parameters for the script and return it as a string. This approach would prevent me from having to embed lengthy JavaScript files as strings.

Below is the directive in question:

directive

 function barchart() {
        return {
            restrict: 'EA',
            replace: true,
            template: `
                  <div id="canvas" class ="panel-body container-fluid">
                    <div class ="ui centered grid">
                        <div>
                            <div id="title"></div>
                            <div id="chart"></div>
                        </div>
                    </div>
                  </div>
                `,
            scope: {
                revenues: "=revenues"
            },
            link: function ($scope, $element, $attrs) {
                $scope.$watch('revenues', function (rev) {

                    if (typeof rev != 'undefined') {
                        $element.append(`<script> (render(${rev}))(); </script>`);
                    }
                });
            }
        }
    }

I am striving for something similar to this, but encountering issues.

render (function that should return a script)

function render(params){
   return (function(){
            $('#chart').append('<p> params </p>');
          })();
}

error

rev is not defined

Answer №1

Enclose the render() function within ${ and }

$element.insert(`<script>${render(text)}</script>`);

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

Having trouble getting a div to slide to the left on hover and collapse on mouseout using Jquery?

Hey there! I need some assistance in completing this code snippet. I have a div with overflow:hidden and a margin-left of 82px. Inside it, there is a share link and a ul list containing three external links. When I hover over the share link, everything w ...

One can pass parameters to a promise's success callback within AngularJS using $q

I have encountered a situation that is similar to the one described in this post, but I am still unsure about how to implement it. I could use some assistance with setting up a successful callback. This is the current functioning code: function getStuff( ...

Tips for centering or aligning a component to the right using Material UI?

Is there an efficient method to align my button to the right of its parent in Material UI? One approach could be using: <Grid container justify="flex-end"> However, this would also require implementing another <Grid item />, which m ...

Combine an array of objects that are dynamically created into a single object

Having trouble transforming the JSON below into the desired JSON format using JavaScript. Current JSON: { "furniture": { "matter": [ { "matter1": "Matter 1 value" }, { "matter2": "Matter 2 value" }, { ...

Posting a string using AJAX to the Java backend through JavaScript

I'm currently working on a comment section for a Web Client. There are two tables involved - one for the comments and another for the users. My goal is to send input data from HTML <input> tags to a Java Service where the data will be processed ...

Preventing Multiple Form Submissions in JavaScript

I'm having an issue with my form submission to Parse where, after adding client-side validation, the data is being double submitted to the database. Despite adjusting my code based on other Stack posts and being new to JavaScript, I'm still expe ...

A chart using JavaScript that displays text values instead of a traditional website

I am a student with no background in programming, however, for my project I need to create a chart based on values from a txt file to display sensor data. I came across a chart that retrieves its values from a website, but I would like to modify it so it c ...

In order to manage this file type properly, you might require a suitable loader, such as an arrow function within a React

Currently, I am in the process of creating an npm package and have encountered a difficulty with the following code: You may need an appropriate loader to handle this file type. | } | | holenNummerInSchnur = Schnur => { | if (this.beurte ...

Middleware in the form of Try and Catch can be utilized to handle errors and

Currently, I am working on developing a backend using node.js with Express. My main goal is to effectively handle any potential status 500 errors that may arise. router.put('/test', async (req, res) => { try { return res.send(await r ...

It appears that the NodeJs Express 4 async function in the model is returning before completion

I'm currently working on organizing my project by splitting the logic into different folders such as routes, views, models, and controllers. Within a model named data (models/datamodel.js), I have implemented two methods to retrieve data for populati ...

Storing the background color in a JavaScript variable

I've been experimenting with creating a fade in and out effect for a background image on a website. I've also been attempting to capture the background color of a div and store it in a variable. Here's what I have tried: elem = document.ge ...

React: The issue with async and await not functioning as expected when using fetch

I am working with an API on a Node server that returns JSON data like this: {"result":[{"ProductID":1,"ProductName":"iPhone10","ProductDescription":"Latest smartphone from Apple","ProductQuan ...

Query parameter is not defined

Can anyone assist me with extracting the ean from the following URL: This NodeJS server processes the request in the following manner: const http = require('http') const port = 3000 const requestHandler = async (request, response) => { ...

The html2canvas script is executing before the $modalInstance is able to be closed

I am currently in the process of setting up a feedback modal within my Angular application that utilizes html2canvas to capture a "screenshot" of the user's current page. However, I have encountered an issue where the html2canvas function is being tri ...

Implement safe instructions through communication between the client and server

I am currently using Fancy WebSockets in Javascript for communication with my php server to support my multiplayer game. At the moment, I am simply sending raw sockets (json) as Sending: {"command": "login", "data": {"id" : "1575","md5" : "6bd8937a8789a3 ...

Guide to automatically closing the calendar once a date has been chosen using owl-date-time

Utilizing Angular Date Time Picker to invoke owl-date-time has been functioning flawlessly. However, one issue I have encountered is that the calendar does not automatically close after selecting a date. Instead, I am required to click outside of the cal ...

Unusual jQuery error notification

Short Receiving Error in syntax, unrecognized expression: [object Object] @ jquery.js:4267 This code snippet is from jQ: Sizzle.error = function( msg ) { throw new Error( "Error in syntax, unrecognized expression: " + msg ); // Line 4267 }; Detaile ...

Issue with firing the React-Redux action has been encountered

I am currently utilizing React along with react-redux, redux and redux-actions. Within my application, I have a specific action that is responsible for verifying the validity of the token stored in localStorage to ensure it is not expired. This action loo ...

Learn how to convert data to lowercase using Vue.js 2

I am attempting to convert some data to lowercase (always lowercase) I am creating a search input like : <template id="search"> <div> <input type="text" v-model="search"> <li v-show="'hello'.includes(sea ...

real-time update of gauge value from soap

I am trying to update the value shown in my justgage widget with the value returned from $("#spanrWS_Measured").text(data[0]);. The current value is 123. Any assistance would be greatly appreciated. See the complete code below. <script src="scripts/r ...