Is there any way to inject the JavaScript stored as a string in AngularJS controllers dynamically?

var dynamicJS = "function DoSomething(value){var x = 1+1  return 2;}"

In the above function, I have to inject dynamically into my AngularJS controller and to be called on selection change of drop-down values which are bound to the AngularJS controller. The reason is JavaScript function would vary based on my each row of data which I have based on my configuration at an application level. I am aware we can make use of $eval but would like to get some better approaches if any.

Can anyone give me any idea on this ?

Note: I am using AngularJS v1.4.5

share
    
Why are you storing a function as a string in the first place? – AJ Funk 53 mins ago
    
    
Per my requirement I have to do some data population or some validations based on the data which I have. In some case I dont need to execute any but for some other case I may need to execute it with the configured JS functions for that data. the JS function is not consistent and I can execute it based on configured for the specific data per my requirement. make sense ?. – Sasi 46 mins ago
    
This is a very dangerous thing to do; it is extremely easy to create attack vectors into your app by modifying these strings. – Claies 41 mins ago

Perhaps try something like:

function myFunc(obj){
    var param = obj.hasOwnProperty('param') ? obj.param : undefined;
    console.log(param);
}

var funcString = "myFunc({ param: 'something' });",
    Construct = new Function(funcString);

Construct();

Haven't tested it to be honest ... but this way you avoid eval().

more info on Function object

share

There are multiple ways to achieve this.

Function

Create a Function and set the body:

var dynamicJS = "var x = 1+1  return 2;"
var DoSomething = new Function("value", dynamicJS );

eval()

While arguably less secure1, eval() can be used.

var dynamicJS = "function DoSomething(value){var x = 1+1  return 2;}"\
eval(dynamicJS);

Caution

Please read this section of the MDN documentation about eval() .

Don't use eval needlessly!

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, third party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.

eval() is also generally slower than the alternatives, since it has to invoke the JS interpreter, while many other constructs are optimized by modern JS engines.

There are safer (and faster!) alternatives to eval() for common use-cases. 1

See a demonstration of these methods utilized below.

var dynamicJS = "function DoSomething(value){var x = 1+1;  return 2;}"
var functionBody = "var x = 1+1;  return 2;";
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('eval').addEventListener('click', function() {
    eval(dynamicJS);
    console.log('DoSomething: ',DoSomething(3));
  });
  document.getElementById('function').addEventListener('click', function() {
    var dynamicFunction = new Function("value", functionBody);
    console.log('dynamic function():',dynamicFunction(3));
  });
});
<button id="eval">click to eval</button>
<button id="function">click to use Function</button>


1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Don't_use_eval_needlessly!

share
1  
Eval can be very Evil! Take care. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…! – mr.void 50 mins ago
1  
Yep - agreed. I have incorporated that info. – Sam Onela 28 mins ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.