Using $eval in Angular to pass a string to an object

Here's the scenario:

"var jsonData={first:{name:'John', age:30}};"    

I am looking to instantiate an object from this string,

The standard JS eval function works perfectly for this purpose, however, when attempting to use $eval I encounter "ReferenceError: jsonData is not defined" and Angular restricts my usage of $eval only to the controller.

Any suggestions on how I can accomplish this task?

Many thanks

Answer №1

Looking for the solution? Check out this post: Angular.js: How does $eval work and why is it different from vanilla eval?

When it comes to AngularJS, $eval and $parse handle AngularJS expressions, not JavaScript code. To understand the distinction between expressions and regular JavaScript, refer to the documentation provided in the link.

I personally tested the expression evaluator for angularjs 1.0.8+ on the reference page. It performed smoothly without any errors. If you need to assign data to a key like `scope.config`, simply skip using the keyword `var`.

"config={general:{instance:'livedemo'}}"

Answer №2

Angular's $eval function is specifically designed to evaluate angular expressions, not general JavaScript code. This typically refers to the expressions used in your HTML like {{expression}}.

When deciding whether to use eval, it's important to consider the source of the string you are evaluating. If you have complete control over it, using eval may be acceptable. However, if there are any doubts about its safety, it's recommended to try parsing the string.

If the string within the curly brackets {} follows proper JSON format, for example:

{"general": {"instance": "livedemo"}}
, you can handle it as shown below:

var s = "var config={general:{instance:'livedemo'}};";
var m = s.match(/var (.*)=({.*})/);
var varname = m[1];          // "config"
var data = JSON.parse(m[2]); // {general: ...}

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

Tips for adding a bounding box to an image received from the server

I've got a python server that is returning a collection of bounding boxes post OCR processing (using Tesseract or similar). "bbox": [{ "x1": 223, "y1": 426, "x2": 1550, &q ...

Start from scratch when establishing the baseline for "defaults."

Struggling to reimagine the _.defaults function from underscore.js, I keep encountering this pesky error: Error message: should copy source properties to undefined properties in the destination object‣ AssertionError: expected { a: 'existing' ...

Exploring the world of three.js, webGL, and GLSL through the magic of random

When using three.js to call a fragment shader, I have a shader that specifies a color for my material in rgb format. I am trying to figure out a way to multiply those colors by a random value. The code I currently have is as follows: gl_FragColor = vec4( ...

Modifying css background in real-time based on the current weather conditions

Is there a way to dynamically change the background image in CSS based on the weather condition? I'm utilizing the wunderground API to retrieve the weather data, which is stored in the weather variable. I am struggling with how to update the backgrou ...

Is there a way to transform a JSON object into a custom JavaScript file format that I can define myself?

I have a JSON object structured as follows: { APP_NAME: "Test App", APP_TITLE: "Hello World" } My goal is to transform this JSON object into a JavaScript file for download. The desired format of the file should resemble the follo ...

Tips for displaying an element for each item chosen in a multi-select box

I currently have a situation where I am rendering for every selected element within my multiselect angular material selectbox. The rendering process functions correctly when I select an element, but the issue arises when I try to deselect one - it just ke ...

Clicking the responsive menu does not reveal the hidden overlay div as expected

Struggling with finding the correct function to open the hidden div of my responsive menu on my new website. Check out my code: https://codepen.io/anon/pen/XRJRGE <a class="page-head__menu" id="js-menu" href="#" onClick="open()">Menu< ...

What causes the 'then' method of my angular service to return a resolved promise instead of the expected value?

I am perplexed as to why the "result" in this code snippet is a resolved promise instead of the actual value: searchService.getLink(vm.queryObject).then(function (result) { console.log(result); }); The implementation for the getLink() function is pro ...

Using Javascript and ExtJS to retrieve the Codemirror Editor using a textarea

Hello to the wonderful stackoverflow community, I recently incorporated a Codemirror Editor into my ExtJSProject like this: addCodeMirrorPanel: function() { this.getAixmFormarea().add(Ext.widget({ xtype: 'textarea', fieldLabe ...

Setting the height of Material-UI TreeView

Looking for advice on how to set a fixed height or dynamically adjust the height of a material-ui TreeView to fit the display? https://i.sstatic.net/40Qlv.png I'd like a scrollbar to appear when the TreeView content reaches a height of 100 pixels, f ...

How can we efficiently iterate through an array in Node.js while making asynchronous calls?

I need to iterate through an array, pushing a new Thing to a list in the process. The Thing itself performs asynchronous calls. However, I am facing an issue where my for loop is synchronous but the new Things are asynchronous, causing the callback to be c ...

Navigating through multiple overlapping scenes in Three.js using Orbit Controls

Seeking assistance with a dilemma involving the use of Orbit Controls with Multiple Overlapping Scenes. To showcase the issue, I made adjustments to the example found at multiple scenes and developed a test specific to my needs. The code can be accessed h ...

Exploring the benefits of integrating Application Insights within ASP.NET 5

My ASP .NET 5 application has been set up to utilize application insights. This application is an angularjs web platform containing only pure HTML, JavaScript, and no server-side code. Here are the steps I followed: Added the Microsoft.ApplicationInsigh ...

The URL for the form action does not match the URL of the current page

Issue: I'm encountering an issue with a form where the form action URL is different from the page URL where the form is located. Page URL = www.page.com Form action = "" Problem: After submitting the form, it redirects to the form action URL inst ...

There was an error in React-Native using Native-base, as a failed prop type with an Invalid props.style key "NativeBase" was supplied to the "View"

Software Versions: React: 16.3.1 React-Native: ~0.55.2 Native-Base: ^2.8.0 Problem Alert: Warning: Failed prop type: Invalid props.style key 'NativeBase' supplied to 'View' Operating Systems: This warning keeps popping up in my r ...

A fatal error has occurred in Node as it is unable to set headers after

Just getting started with nodeJs and I'm attempting to read a file from the system. It seems like I can view the file content in the console, but for some reason it's not displaying in the browser. Any ideas what I might be overlooking? var myD ...

Positioning html images to overlap each other without losing the ability to click

Currently, I am facing a challenge with positioning two images over each other. The back image should be at the bottom, while the center image needs to be on top of it. Additionally, there is a requirement for placing a random link (in this case google.com ...

What is the best way to automatically close a parent popup window when the child popup is

Currently, I am developing a web application using Angular that requires managing nested popups. Specifically, in my scenario, I initiate Popup 1 and from within that popup, I trigger another popup (Popup 2) upon clicking "delete." My goal is to ensure tha ...

Undefined value is returned for Vue 3 object property

Is there a way to extract additional attributes from the Keycloak object ? Currently, If I try, console.log(keycloak) it will display the entire keycloak object. Even after reloading, it remains in the console. However, when I do, console.log(keycloak.t ...

Expand the <div> by clicking on it, then hover away to return it to its normal size

One interesting feature I have on my website is a <div> that expands when clicked, and returns to normal size with another click. However, I am looking for something a bit different... What I want is for the <div> (with the class name .topHead ...