1

I have a function that is assigned to a variable. I then assign this variable to $scope with the hope that it will call the function. But it doesn't work:

var func = myFunction("argument");
$scope.func;

I also tried:

var func = myFunction("argument");
$scope[func];

Is there a way I can get this to work?

Chris Paterson
  • 1,129
  • 5
  • 21
  • 31

3 Answers3

4

You have a few things missing:

    var someFn = function (arg) {
           //do something with arg
    }

You can then add this function to the scope:

$scope.fnOnScope = someFn;

You can then execute the function:

$scope.fnOnScope("argument");

Alternatively, you can just put the function on the scope in the first place.

Mark Sherretta
  • 10,160
  • 4
  • 37
  • 42
  • I made a few mistakes when formulating my question. The variable ``func`` is assigned to text, not a function. But, this text represents a function. That's why I want to assign it to ``$scope``. – Chris Paterson Jan 25 '14 at 17:40
  • Oh, I understand. So, func is assigned a string value that is the name of a function, correct? If this function is on the scope, you can execute it with $scope[func](); The function to execute must be defined on the scope for this work. – Mark Sherretta Jan 25 '14 at 22:28
0

That sounds a little dangerous (evaluating the function to execute "on the fly") but assuming that's what you want, it should be fairly easy if you place the function on an object.

var availableFunctions = {
   functionToCall: function(arg) {
      console.log(arg);
   }
};

var func = myFunction("argument"); // assume this returns "functionToCall" 
$scope.func = availableFunctions[func]; 

Is that closer to what you are looking for?

Jeremy Likness
  • 7,531
  • 1
  • 23
  • 25
0

If the func is the name of the function that's already declared in window scope. Try:

var func = myFunction("argument");
window[func].call($scope);
Khanh TO
  • 48,509
  • 13
  • 99
  • 115