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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
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?

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.