Leveraging the power of AngularJS to run JavaScript functions saved as strings

Is it possible to dynamically inject JavaScript code that is stored in a string into AngularJS controllers?

var dynamicJS = "function DoSomething(value){var x = 1+1  return 2;}"

I need to inject the above function dynamically into my AngularJS controller and have it executed when there is a selection change in a drop-down menu. The values in the drop-down are bound to the AngularJS controller. Each row of data may require a different JavaScript function, which is determined by application configuration. While I am aware of using $eval, I am looking for better approaches if they exist.

Does anyone have any suggestions or ideas on how to achieve this?

Note: Using AngularJS v1.4.5

Answer №1

There are various methods to accomplish this task.

  • Using a Function Object

    To achieve this, you can create a Function by passing the necessary argument (such as value) and defining the functionBody:

    var dynamicJS = "var x = 1+1;  return 2;"
    var DoSomething = new Function("value", dynamicJS );
    
  • Using eval()

    Another approach is to use eval(), although it is considered risky:

    var dynamicJS = "function DoSomething(value){var x = 1+1  return 2;}"
    eval(dynamicJS);
    

    If your application is internal and isolated from external influences, this method may suffice. However, caution is advised, as highlighted below.

    Be Cautious

    The MDN documentation regarding eval() emphasizes the risks associated with its usage:

    Avoid Unnecessary eval() Calls

    eval() is a powerful yet dangerous feature that executes code within the caller's context. If the input supplied to eval() is tampered with malicious intent, it could lead to execution of harmful code on the user's device with the permissions granted to your application or extension. Additionally, third-party scripts can access the scope in which eval() was invoked, potentially enabling security vulnerabilities not present when using a similar approach with Function.

    eval() also tends to be slower compared to alternative techniques, as it requires invoking the JavaScript interpreter every time, unlike other optimized constructs supported by modern JavaScript engines.

    For most common scenarios, there exist safer and more efficient alternatives to eval(). 2

Below, you'll find a demonstration showcasing these methodologies in action. Click on the respective buttons to observe their output in the console.

var dynamicJS = "function DoSomething(value){var x = 1+1;  return 2;}"
var functionBody = "var x = 1+1;  return 2;";
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('eval').addEventListener('click', function() {
    eval(dynamicJS);
    console.log('DoSomething(3) -> ',DoSomething(3));
  });
  document.getElementById('function').addEventListener('click', function() {
    var dynamicFunction = new Function("value", functionBody);
    console.log('dynamic function(3) ->',dynamicFunction(3));
  });
});
<button id="eval">click to eval</button>
<button id="function">click to use Function</button>


1

2https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Don't_use_eval_needlessly!

Answer №2

It seems like the most straightforward approach would involve parsing the String and utilizing the function constructor.

One possible implementation could look something like this:

var PerformAction = new Function('input', 'let result = input * 2; return result;');

Answer №3

Why not give this a shot:

function customFunc(data){
    var info = data.hasOwnProperty('info') ? data.info : undefined;
    console.log(info);
}

var functionInput = "customFunc({ info: 'example' });",
    Generator = new Function(functionInput);

Generator();

I haven't actually tested it myself... but using this method can help you avoid utilizing eval().

For more details, check out the Function object documentation.

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

Troubleshooting: Angular 6 Renderer2 Issue with Generating Dynamic DOM Elements for SELECT-Option

Currently, I am attempting to dynamically create a select option using Renderer2. Unfortunately, I am facing difficulties in creating the <Select></Select> element, but I can confirm that the <options> are being successfully created. Due ...

Customize the filename and Task Bar name for your Electron app when using electron-packager

My application uses electron packager to build the app on Mac. Here is my package.json configuration: { "name": "desktop_v2" "productName": "desktop v2", "version": "1.0.0", "license": "MIT", "scripts": { "build": "node --max_o ...

Tips for displaying a loading indicator above a form

I've been struggling to figure out how to display a loading indicator on top of my form without messing up the styling... My goal is to show the loading indicator when any action, like deleting an item or changing quantity, is triggered in React.js + ...

The Angular application is receiving a 404 error when trying to access the .NET Core

Having trouble calling a method in the controller via URL, as I keep encountering a 404 error. What could be the issue? API Endpoint: http://localhost:5000/Home/HomeTest /*.net core web-api*/ namespace MyApp.Controllers { Route("api/[controller]") ...

Utilize CSS to format the output of a script embedded within

When I embed the following script in my HTML, the output doesn't have any styling. How can I style the script output to blend well with the existing HTML structure? I tried accessing the output by ID, but couldn't figure it out. <script> ...

What is the best way to process an API call entirely on the server without revealing it to the client?

Seeking guidance on a technical issue I've encountered. On my website, x.com, a form submission triggers an API call to y.com, yielding a JS hash in return. The problem arises when Adblocker Plus intercepts the content from y.com, causing it to be bl ...

What is the process for including a field specific to a date in a form?

I need the user to select a month and year. In one column, there will be the days of the month they selected [e.g. 1-30]. Users can then add habits in other columns. I want users to be able to input an 'X' for each habit row on a specific date [e ...

The tooltip in a scrollable container of Highcharts moves along with the content as it scrolls

I am currently facing an issue with my Highcharts instance that is displayed within a scrollable container. In addition, I have set the tooltip.outside option to true so that the tooltip always appears on top even if it exceeds the chart svg. The problem ...

Spin the AngularJS icon in a complete 360-degree clockwise rotation

Hey there! I'm new to Angular and I'm trying to create a button that will make an icon inside rotate 360 degrees when clicked. Right now, the entire button is rotating instead of just the element inside it. I want only the "blue square" to rotate ...

Tips for styling tooltips in rc-slider

I am currently using the react library rc-slider and I am looking to add a tooltip feature to display the current value. I found guidance on how to do this from a post on the rc-slider GitHub page. However, I encountered an issue where my slider position b ...

Encountered an issue retrieving tweets from the Twitter API 1.1

I recently completed an online tutorial from this site: However, I'm encountering an error message that simply says 'error: ' without any additional information. To start, here is my PHP script used to fetch the JSON output: <?php sess ...

Display HTML code within a data attribute

I have a function that modifies an element from OpenLayers. In the official documentation, it mentions that the property label accepts either HTML or a string. methods: { onUpdatePosition (coordinate) { this.deviceCoordinate = coordinat ...

The npm module parsing has encountered an error... It appears that a suitable loader is required to process this file format

Recently, I made changes to an open-source code that was working perfectly until yesterday. I can't seem to figure out what went wrong as I didn't make any significant changes. Despite searching on Stack Overflow for a similar issue, my lack of k ...

Utilizing Subdirectories in a Command Manager

My goal is to organize my commands into sub folders, but for some reason my bot is not recognizing the commands inside those folders. Strangely, no error message is being displayed. const fs = require('node:fs'); const Discord = require('dis ...

The process of loading the Facebook like script using $.getScript is causing an issue where the

How can I make the Facebook like button display properly on my HTML page? I have successfully loaded scripts and divs for Twitter, Google +1 buttons, but the Facebook like button script is not displaying the button. The alert shows that the script is exec ...

The integration between Javascript, PHP, and SQL Server does not display the retrieved data

I am a beginner in PHP and have limited knowledge of Javascript. I am attempting to create a chronometer where the time limit is retrieved from a SQL SERVER database. However, when I assign the value obtained in PHP to a Javascript variable, it returns -1. ...

Problem with character encoding in Node.js

I am encountering an issue while retrieving data from a request, as the formatting or encoding is not matching my requirements. Attempted to address this by setting the encoding with req.setEncoding('utf8') The expected string should appear as: ...

Fixed navbar at the bottom of the page that transitions to static when scrolling reaches a certain location

Is it feasible to achieve this using Bootstrap v3? After conducting extensive research, it appears that a custom solution may be necessary. In essence, I am working with a navbar positioned at the bottom of the content area. Upon page load, if the navbar& ...

The template failed to load on AngularJS post-compilation

Following the build of my Angular app, I encountered this error message: [$compile:tpload] Failed to load template: app/app.html (HTTP status: 404 Not Found). Seeking assistance from you all!!!!! app.html <div class="root"> <div ui-view> ...

Angular JS Tab Application: A Unique Way to Organize

I am in the process of developing an AngularJS application that includes tabs and dynamic content corresponding to each tab. My goal is to retrieve the content from a JSON file structured as follows: [ { "title": "Hello", "text": "Hi, my name is ...