0

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

Ronald lb
  • 3
  • 2

2 Answers2

0

Angular's $eval is not made to evaluate any javascript expression but an angular expression, i.e. 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, i.e.: {"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: ...}
floribon
  • 19,175
  • 5
  • 54
  • 66
  • first thanks for the replay, but my string is doesn't have the right Quotes("), so I can't use the JSON.parse, any other idea of how to do it? – Ronald lb Jan 27 '15 at 19:50
  • Well then you will need to use `eval`, but maybe you could find a way to avoid the whole thing? Where does this string-code come from? You could evaluate only m[2] and make sure no funciton is invoked by removing any parenthesis: `eval("var data = " + (m[2].replace(/\(\)/,''))); ` – floribon Jan 27 '15 at 23:45
0

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, i.e. scope.config, then you can discard the keyword var.

"config={general:{instance:'livedemo'}}"
Community
  • 1
  • 1
rubish
  • 10,887
  • 3
  • 43
  • 57