Steps for running the function saved in variable `x`, with the value `function(){alert('a')}` assigned to it

How can I achieve this using javascript?

var x = 'function(){ ... }'
x = x.toFunction();
x();

Previously, I used var x = '...'; eval(x), but I have learned that this method is inefficient and slow.

To provide some context, my goal is to execute a function passed as an attribute to <loaded>. For instance:

HTML

 <p loaded="test, function(){alert('it worked!')}">

AngularJS

.directive('loaded', function() {
 return {
  restrict: 'A',
  link: function(scope, elem, attr) {
   var paramOne = attr.loaded.substr(0, attr.loaded.indexOf(',')) //paramOne = test
   var paramTwo = attr.loaded.substr(paramOne.length+1).trim() //paramTwo = "function(){alert('it worked!')"
   if (paramOne==='test') paramTwo() //Previously, eval(paramTwo) was used here
  }
 }
}) 

Check out the jsfiddle for more information.

*EDIT: * I am hesitant to post this as the final answer as I'm still uncertain. There might be a better approach.

var x = "function(){alert('it worked!')";
x = new Function('(' + x + ')()');
x(); //this triggers an alert saying 'it worked!'

Please advise if my edit is a valid solution or if there is a different way to go about it

Answer №1

I haven't had a chance to test out this code, but I believe the concept is as follows:

.directive('loaded', function() {
  return {
    restrict: 'A',
    scope: {
     fn: '&'
    },
    link: function(scope, elem, attr) {
      var paramOne = attr.param1;

      if (paramOne === 'test'){
        scope.fn();
      }
    }
  }
});

fn refers to the function that should be executed within the link function. You can define this function within the controller. param1 acts as a parameter that needs to be passed in another attribute (for example, with the value of 'test' for this attribute).

<p loaded param1='test' fn='fn()'>

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

Utilize typehead.js in Python Django to retrieve an updated data list directly from the database

file.js var source = new Bloodhound({ hint: false, datumTokenizer: Bloodhound.tokenizers.obj.whitespace("description"), queryTokenizer: Bloodhound.tokenizers.whitespace, // /a_c/p_s/?term=d&category=all remote: "/a ...

In order to utilize the componentDidUpdate lifecycle method, I passed props to the Outlet component while nesting it

I am currently using react-router-v6 and encountering some issues with my configuration. I have implemented nested routing with layouts according to the following settings. App.js <BrowserRouter> <Routes> <Route exact pat ...

Attempting to manipulate information within the @click event handler embedded within a v-for loop

I am using a v-for loop to select dialog boxes that I want to open. <v-card @click="page.model = true"> In this code, page.model is being used as the v-model for a v-dialog component. data() { return { dialog1: false, dia ...

How can I troubleshoot the overflow-y problem in a tab modal from w3 school?

https://www.example.com/code-sample overflow: scroll; overflow-y: scroll; When I type a lot of words, they become hidden so I need to use overflow-y=scroll. Despite trying both overflow: scroll; and overflow-y: scroll;, I have been unable to achieve the ...

Using jQuery to dynamically insert a table row with JSON data into dropdown menus

I'm working on a web form that includes a table where users can add rows. The first row of the table has dependent dropdowns populated with JSON data from an external file. Check out the code snippet below: // Function to add a new row $(function(){ ...

Tips for successfully implementing an Ocrad.js example

I've been working on an OCR (optical character recognition) web application and stumbled upon the Ocrad.js JavaScript library Ocrad.js. It seems like a perfect fit for what I need, but unfortunately, I'm having trouble getting it to function prop ...

Generate a sequence of years without relying on the range function

Is there a different approach to generating this array without relying on the range function? Below is an illustration of what I want, but without utilizing the range method. const years = myCustomArrayGeneration(1990, getYear(new Date()) + 1, 1); ...

What is the process for obtaining an API Key in order to access a service prior to authorization?

Alright, I have this app. It's a versatile one - can run on mobile devices or JavaScript platforms. Works across Windows, Apple, and Android systems. The app comes equipped with a logging API that requires an API key for operation. Specifically, befo ...

How to upload a document to Alfresco using JavaScript API

I am facing an issue while attempting to upload a file from a node application to my local Alfresco server. I have been able to login, create, and delete folders successfully, but I am encountering difficulties when trying to upload files. let AlfrescoApi ...

What is the best way to convert a recordset to an array using React?

I'm attempting to create an array by retrieving data from a SQL recordset: +------------+------------+------------+ | start_type | field_name | start_text | +------------+------------+------------+ | 0 | Field1 | some text. | +----------- ...

Copying JSON Data in JavaScript: A Guide

Seeking advice on how to duplicate JSON within the same JSON at various hierarchy levels. Take a look at this example JSON below: Initial code snippet looks like this: { "data": { "moduleName": { "content": { "modul ...

Customizing AngularJS Scripts to Include Target Blank

I'm feeling a bit lost. I need to include a target="_blank" on my anchor link. The issue is that the anchor tag is linked to a script in angular. I am not familiar with this JavaScript framework. I have tried searching through the documentation for po ...

Ways to verify if a Discord.js snowflake is present in a collection of other identification numbers

I'm currently developing a Discord.js bot and I want to create a system where only specific IDs listed in a JSON file can trigger certain commands. However, I'm unsure about how to implement this logic within an if statement. if (message.author. ...

Setting up Npm Sequelize Package Installation

Could use some help with setting up Sequelize. Here's the current status: ...

The subsequent menu selection will be based on the chosen menu value

I am attempting to accomplish the following: https://i.sstatic.net/JffUWC02.png Essentially, I need a select options menu with labels where selecting an option will display a corresponding value. These values should then become labels for a second selec ...

Is there a way to prevent the imported JQuery from causing issues with current code implementations?

Being a novice developer in Html/Javascript/CSS/Jquery coding, I recently encountered an issue while integrating Jquery into my project. When I imported Jquery, the styling of simple buttons went haywire. Jquery worked perfectly fine when using its classes ...

Angular- Table button placement

I have a requirement where I need to display a button in a table, but the button should only show when the "name" value is set to "False". If the "name" value is set to "True", then the button should not be displayed. This is my Json data: [ { ...

Is it possible to test the JEST configuration for the node_modules even when it is turned

I'm currently integrating Jest tests into an existing codebase, but I've encountered an error that's giving me some trouble. Jest came across an unexpected token Typically, this means you're trying to import a file that Jest can& ...

When using Google Maps in an Android webview, an error occurs stating that the user has denied geolocation

I'm having trouble loading Google Maps v3 (Javascript) in an Android web view An error keeps occurring: User denied geolocation Using Ionic, it works flawlessly in desktop Chrome (ionic serve) and iOS devices. The error only appears on Android. ...

What are some ways to enhance the opacity of a Material UI backdrop?

I'm looking to enhance the darkness of the material UI backdrop as its default appearance is not very dark. My goal is to make it dimmer and closer to black in color. ...