Executing javascript functions stored as strings using AngularJS

Is there a way to add JavaScript code stored in a string in AngularJS controllers dynamically?

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

I need to dynamically inject the above function into my AngularJS controller and call it when I change the selection of the drop-down list whose values ​​are bound to the AngularJS controller. The reason is that the JavaScript function will vary depending on my every row of data that I based on my configuration at the application level. I know what we can use $eval, but would like to get some better approaches if they exist.

Can anyone give me any idea on this?

Note. I am using AngularJS v1.4.5

+4
source share
3 answers

There are several ways to achieve this.

  • Function object

    Create a Function by passing one parameter (i.e. a value) and functionBody as parameters:

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

    Although perhaps more dangerous is 1 eval () .

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

    Because you mentioned in the comment

    "This is an intranet application and is not going to the outside world. There is no problem for this in this matter."

    this will probably be fine, but please read the section below.

    Attention

    From this section of the MDN documentation about eval () :

    Do not use eval unnecessarily!

    eval() - , . eval() , , -/. , , eval(), , Function .

    eval() , , JS-, JS.

    ( !) eval() .2

. , . , , .

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(3) -> ',DoSomething(3));
  });
  document.getElementById('function').addEventListener('click', function() {
    var dynamicFunction = new Function("value", functionBody);
    console.log('dynamic function(3) ->',dynamicFunction(3));
  });
});
<button id="eval">click to eval</button>
<button id="function">click to use Function</button>
Hide result

1fooobar.com/questions/11873/...

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

+2

, String, .

- :

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

, - :

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

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

Construct();

, ... eval().

+1

Source: https://habr.com/ru/post/1674130/


All Articles