简体   繁体   中英

How to use $eval to pass string to obj - Angular

I have this string:

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

And I want to create an object based on that string,

the thing is that using the normal JS eval function everything works great, but using $eval I get "ReferenceError: config is not defined" and angular only let me use $eval on the controller.

someone with an idea of how I can do it?

Thanks

Angular's $eval is not made to evaluate any javascript expression but an angular expression, ie usually what you write into your HTML such as {{expression}}

Now it all depends on where your string to be evaluate comes from. If you have total control over it it is fine to do an eval . However if you are not sure it is safe, you can try to parse it.

If your string into the {} was proper JSON, ie: {"general": {"instance": "livedemo"}} , then you could have:

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

This question might have your answer, Angular.js: How does $eval work and why is it different from vanilla eval?

$eval and $parse don't evaluate JavaScript; they evaluate AngularJS expressions . The linked documentation explains the differences between expressions and JavaScript.

I tried the expression evaluator for angularjs 1.0.8+ at the linked page. It is working without giving any exceptions. If you want to set some data in at a key config on the scope, ie scope.config , then you can discard the keyword var .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM