0

I want to call function dynamically based on variable and the variable has the function name , for example

var fun =function1(1,2)

after sometimes variable fun can have function

fun= function2(2,3)

its just an example to explain my scenario

and then I want to call it from my html

html

<button ng-click="{{fun}}>call</button>

fun can have function1 and function2 sometimes

1
  • dont use {{}} if you want to access a variable. just use the variable name Commented Jan 8, 2018 at 7:54

2 Answers 2

1

Because functions are first-class citizens in JavaScript, we can pass them around like we would with any other variable.

See this JSFiddle example that alternates f1 and f2 when you click on Change Handler.

HTML

<body ng-app="exampleApp" ng-controller="appCtrl">
    <div>
        <h3>{{name}}</h3>
        <br>
        <button type="button" class="btn btn-primary" ng-click="fun()">Show Name</button>
        <button type="button" class="btn btn-primary" ng-click="changeClick()">
          Change Handler
        </button>
        <br>
        <h3 ng-show="clicked">You did it {{name}}</h3>
    </div>
</body>

JavaScript

var app = angular.module('exampleApp', []);

app.controller('appCtrl', function($scope){

    function f1() {
        $scope.name = "Chris";
    }

    function f2() {
        $scope.name = "Harry";
    }

    $scope.fun = f1;

    $scope.changeClick = function() {
      if($scope.fun === f1) {
        $scope.fun = f2;
      } else {
        $scope.fun = f1;
      }
    };

    $scope.name = "Default";
});

In the example above, changeClick alternates the value of fun

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

2 Comments

what if functions have parameter too?
No problem -- you would still change them the same way, regardless of whether they have parameters or not. Just make sure you pass in the parameters when you call the function in ng-click. For example ng-click="fun(param1, param2)"
0

dont use {{}} if you want to access a variable. just use the variable name

function foo() {
    console.log("executing foo");
}

$scope.fun = foo;

<button ng-click="fun()">call</button>

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.