Retrieve JavaScript functions as JSON or text in AngularJS and execute them

Currently, I am working on developing an AngularJS application and have come across a particular challenge that needs to be addressed:

After making a web service call, I receive JavaScript code that looks like this:

{ 
 "script":"function foo(a, b) { c = bar(a,b) $scope.c = c } function bar(a,b) { return a+b }"
}

My goal is to invoke the foo(a,b) function in my AngularJS application and have the property c within my $scope reflect the result from the bar(a,b) function.

Is it feasible for the foo(a,b) function to access $scope? What if there are existing functions named foo() or bar() within my application?

I've tried exploring solutions using eval and Function() features in JavaScript. However, I'm uncertain whether those can resolve my issue effectively.

pass function in json and execute

Your assistance or recommendations on this matter would be highly valued :)

Cheers,

Kevin

Answer №1

One way to approach this issue is by reconsidering the structure of your code. It's a cause for concern if you're passing around code as text and then using eval to execute it. It's recommended to refactor your code to use more standard coding practices whenever possible.

Setting that aside, someone inquired about using the eval and Function() capabilities in JavaScript. However, they expressed uncertainty about whether this method would solve their problem effectively.

Indeed, it can work. The eval function operates within the scope where it's invoked, which means any variables created inside will only exist within that specific context or function call unless preserved elsewhere.

For instance:

function evaluate($scope) {
    eval(yourString);
}

This will confine any new variables like 'foo' and 'bar' to the evaluate function itself, ensuring access to the $scope argument only while executing the function.

It's essential to exercise caution when utilizing eval, ensuring the script originates from a trustworthy source.


An important distinction to note is that the behavior of eval changes when indirectly called through a variable instead of directly:

var e = eval;
e(yourString);

In such cases, the evaluation occurs globally rather than within the same local scope. This explains why some opt for unconventional methods like (0,eval)(string) to trigger eval globally, whereas assigning eval to a new variable like globalEval followed by calling globalEval(string) provides better clarity and maintainability.

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

The method .setArray has been deprecated in THREE.BufferAttribute. Instead, please use BufferGeometry .setAttribute for unindexed BufferGeometry operations

Seeking assistance with updating the webgl-wireframes library code to the latest version of threejs. The current function is generating the following errors: Uncaught TypeError: THREE.Geometry is not a constructor THREE.BufferAttribute: .setArray has ...

Comparing strings in AngularJS

Struggling to compare two strings in AngularJS, I've come across various examples online. From what I understand, there are different methods like angular.equals(str1, str2), ===, and == if you're certain both are strings... Despite trying all t ...

Set the key for all elements in a sibling array to be the same key

Here is a sample input JSON: { "some_key": "x", "another_key": "y", "foo_id": 123, "all_foo": [ { "foo_name": "bar1" }, { "foo_name": & ...

Adding navigation buttons to a Material-UI Select component: A step-by-step guide

Currently, I have integrated a Select component from MUI and it is functioning well. When an item is selected from the list, the router automatically navigates to that location: This is the snippet of code being used: export default function SelectLocatio ...

Encountering difficulties accessing the array in the controller through ajax

Having trouble receiving an array of data from AJAX to the controller. $.ajax({ type: "POST", url: "/Home/List", traditional: true, contentType: 'application/json', data: { "Query&quo ...

Customizing the styling of buttons in Highcharts is disabled when in full screen mode

I've integrated highcharts into my Angular application and included a custom button inside the chart to navigate users to another page. However, I encountered an issue when trying to fullscreen the chart using the export menu. The position of the cus ...

Nginx and Socket.io: Issues with client-server connection not functioning properly

Hello everyone! I am currently in the process of deploying my application, which utilizes React and NodeJs. However, I have encountered an issue with integrating Socket.io with Nginx. My approach involves editing the Nginx file using the command: sudo ...

Strange anomalies arising in frontend Apollo and GraphQL integration

Currently, I am working with nuxt.js and apollo. One issue I am facing is that when I click a button, it sends a request to the graphql server. The strange part is that the first time I click the button, everything works as expected. However, when I clic ...

What is the best way to show a macOS progress pie loading icon alongside files?

While using macOS, a pie loading icon appears next to a file during downloading or transferring. To illustrate, here is an example of a file being downloaded from Chrome: I am interested in implementing a similar feature in my Electron/Node application. ...

"Discovering the missing numbers in an array using JavaScript - a step-by-step guide

I have a series of numbers in a string, such as "3 -1 0 5". My goal is to create another string that lists the missing numbers from the original sequence once it has been sorted. For example, if the original array is sorted as [-1, 0, 3, 5], then ...

How to choose multiple checkboxes in AngularJS by utilizing the shift key and mouse click feature?

Is it feasible to utilize shift and mouse click for selecting multiple elements on a table using AngularJS? In my table, the first column consists of checkboxes and I am interested in employing the SHIFT key along with mouse clicks to select several rows ...

Recording Audio Using ReactJS

I am exploring ways to record audio using ReactJS and save it on my Node server. Initially, I attempted to utilize the "react-audio-recorder" module but encountered issues when attempting to record multiple audios consecutively. Additionally, I experiment ...

Encounter a 401 error code while attempting to fetch data from CouchDB using an AJAX request

I attempted to make an AJAX call in a JavaScript file to fetch data from CouchDB. Unfortunately, I encountered a 401 error message: Failed to load resource: the server responded with a status of 401 (Unauthorized) This is an extract of my JavaScript cod ...

What are some ways to incorporate inline TypeScript Annotations into standard JavaScript code?

If you're using VSCode, there's a new feature that allows you to implement type checking for traditional JavaScript files. There are instances where I wish to specify the type of a variable or parameters in a method or function to enhance auto-co ...

Guide to efficiently utilizing flex to horizontally position two elements next to each other in a Material UI and ReactJS environment

I have successfully achieved side-by-side components of two cards from Material-UI. However, I am facing an issue when expanding one of the cards. The problem is that Card 1 automatically expands to match the size of Card 2 when Card 2 is expanded, even th ...

Issue with Angular search feature failing to properly filter results

I am looking for a way to filter JSON data by typing in a name and only displaying listings that contain that specific name. Currently, the results are just hiding other names but still showing all listings. How can I configure the filter to only show movi ...

When importing data into MongoDB, the system can sometimes throw an error due to a duplicate key index, which can

Suppose I have two separate JSON files that I want to import into the same collection without combining or updating the current documents. Is there a way to disregard the existing _id keys during the import process and have all 6 documents from both files ...

Issue encountered when attempting to invoke a service from an Angular component within an office.js dialog

Our application utilizes Angular 5 and integrates Office.js to interact with Microsoft Office Word documents. Step 1: We use office displayDialogAsync to load the component. https://i.sstatic.net/uhT66.png Step 2: Inside the attribute-users component, an ...

Is it possible to integrate HTML pages as sections within an HTML file using AngularJS?

There are three individuals each working on separate sections of a webpage. One is focusing on moving images, another is devoted to the tab section. This begs the question: 1) Is it feasible to embed all these HTML sections into a single HTML page and dis ...

Is there a method in Express to verify which URL a post is being sent to?

At the moment, I am using express to proxy my session creation URL in the following manner: app.post('/sessions', (req, res) => { // Code goes here }) The code that is used for this proxy also needs to be applied to my /confirmation endpoi ...