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
-
dont use {{}} if you want to access a variable. just use the variable namecute_programmer– cute_programmer2018年01月08日 07:54:44 +00:00Commented Jan 8, 2018 at 7:54
2 Answers 2
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
2 Comments
ng-click. For example ng-click="fun(param1, param2)"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>