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

Parsing JSON as a sequence of individual characters

Currently encountering an issue and seeking guidance from anyone who may have experienced this before and knows what's going on. Utilizing $resource to fetch data from our WebAPI. (angularJS controller code) Controller.service.common.GetData.get({ ...

Exploring the functionality of promises in JavaScript

Currently, I am using the most recent version of Angular. The code snippet I've written looks like this: $q.all({ a: $q.then(func1, failHandler), b: $q.then(func2, failHandler), c: $q.then(func3, failHandler), }).then(func4); Is it guaranteed ...

Assign a directive attribute in AngularJS using a controller

Currently I am utilizing the Angular Bootstrap typehead directive, and its configuration in HTML is as follows: <div ng-controller="search"> <input typeahead-focus-first="false" /> </div> I'm wondering if it's feasible to se ...

Is extracting the title of an image from Flickr?

I have a JavaScript code that randomly pulls single images from Flickr every time the page is refreshed. Now, I want to add a feature where the title of the image is displayed when it's hovered over. However, I've been searching for a solution fo ...

Unleashing the power of Sharepoint 2013 Rest API: Effortlessly creating multivalue

Attempting to save values to a multi-value field, specifically a survey list column, with the following code: $.ajax({ url: "somesitecollection/_api/web/lists/getByTitle('survey')/items", type: "POST", contentType: "application/json;oda ...

The variable is constantly reverting back to its initial value

Here is the code snippet: function send() { var nop = 6; var send_this = { nop: nop }; $.ajax({ type: "GET", data: send_this, url: "example.com", success: function(r) { ...

Implementing icon display upon click in a Meteor application

Currently, I am in the process of developing an application using meteor and within one of the templates, I have the following code snippet. <h3> <b> <a class="viewed" href="/jobdetails/{{_id}}">{{title}}</a> </b> ...

When attempting to retrieve data in JSON format from the Google Directions API, sometimes the returned data is empty

As a beginner in the world of programming and iOS development using Swift, I am currently facing an issue while attempting to create a route between two points. func getDirections(origin: String!, destination: String!, waypoints: Array<String>!, tra ...

Choose a specific JSON attribute by evaluating other elements within an array with JSONPath

I am presenting a JSON array that I have sampled: { "data": { "list": [ { "id": 192, "name": "John Black", "username": "jblack", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_ema ...

Locate the database user based on any parameter provided in the request

I need to search for users in the database using any of three different fields. In Postman, I have set up the following paths: http://localhost:8082/api/users/617473029f80eda3643a7fdd http://localhost:8082/api/users/Michael http://localhost:8082/api/use ...

Create a JavaScript script within a CSS file

I'm attempting to create this using only CSS: Codepen and I would like to achieve the same effect but solely with CSS. This is what my CSS looks like: .text{ --a: calc(var(--a);*0.82+(1.5-var(--b);)/10); --b: calc(var(--b);+var(--a);); transfor ...

What could be causing the ajax request to not go through?

Check out this function I created that triggers an event when any inputs in an HTML form are changed. Function Snippet: function customEvent(form, element) { var timer; $(element).keyup(function () { clearTimeout(timer); if ($(ele ...

Angularjs - How come I am able to modify an object but not the list (ng-repeat) from a separate view?

After updating the customers object in the console, I noticed that the list (ng-repeat) is not reflecting the changes. What should I do? Interestingly, it works fine when I implement this function and view2.htm's HTML inside page.htm. HTML "page.htm" ...

Arranging an Array of Arrays Containing Strings

Looking for a solution to sort an array containing arrays of strings? A similar issue was discussed here. Here is the array in question: var myArray = [ ['blala', 'alfred', '...'], ['jfkdj', ...

I am encountering an error that states: UnhandledPromiseRejectionWarning: TypeError: Unable to retrieve the property 'buffer' as it is undefined

I am facing an issue with my code where I am unable to upload new files to my website. Can someone help me understand what might be causing this problem? const multer = require("multer"); const upload = multer({ storage: multer.memoryStorage() ...

Setting up the Angular 2 router to function from the /src subfolder

My goal is to create two separate subfolders within my project: src and dist. Here are the key elements of my application: root folder: C:\Server\htdocs\ app folder: C:\Server\htdocs\src index.html contains <base href="/ ...

Is there a way for me to streamline the process of logging in using either Google or Facebook?

Is there a way for me to automate the scenario if I'm unable to locate the element using Appium Uiautomator? https://i.stack.imgur.com/Rjji4.png ...

What could be causing PySpark to encounter a JSONDecodeError while trying to convert a string from a Kafka topic into a dictionary?

Utilizing Spark Structured Streaming to ingest data from a Kafka topic in JSON format for transformation within Spark has hit a roadblock. The initial phase involves reading records as strings and converting them into dictionaries using Python's json ...

Dynamic Bodymovin motion graphics

I'm trying to figure out the best way to embed a bodymovin exported file on my website so that it is responsive, maintains the correct aspect ratio of the logo and fonts, and fits within the borders of the site. Does anyone have any suggestions? Appr ...

Struggling with the addition of the 'Other' option in React manually. Any tips or suggestions?

I've encountered a slight issue regarding the functionality of my React Component below. Specifically, I want users to have the ability to enter a poll category that is not listed in the select component options by using an input field. This scenario ...