How to invoke a function as dynamically string in AngularJS?

Issue

How to use a function assigned variable in ng-click?? I have tried three ways below, but that’s also not working.

Could you please let me know is it possible or not??? if yes, then how?

var app = angular.module("app", []);
app.controller("name", function($scope) {

 $scope.showname = function()
 {
 alert("Ramesh");
 }
 
 $scope.variable1 = $scope.showname;
  
 $scope.variable2 = "showname()";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="name">
<button type="button" ng-click="variable1" tabindex="10003" >Not working 1 </button>

<button type="button" ng-click="$scope[variable2]()" tabindex="10003" >Not working 2 </button>

<button type="button"  ng-click="variable2" tabindex="10003" >Not working 3 </button>

<button type="button" ng-click="showname()" tabindex="10003"> working </button>
</div>

Solution

You can use $scope.$eval method and invoke the function like variable2().

$eval method don’t evaluate JavaScript; they evaluate just AngularJS expressions.

Also, for the below line

$scope.variable1 = $scope.showname;

You are just keeping a reference to your showname function. You have to invoke it

<button type="button" ng-click="variable1()" tabindex="10003" >Not working 1 </button>
var app = angular.module("app", []);
app.controller("name", function($scope) {

 $scope.showname = function()
 {
 alert("Ramesh");
 }
 
  $scope.variable1 = $scope.showname;
  
  $scope.variable2 = $scope.$eval("showname");
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="name">
<button type="button" ng-click="variable1()" tabindex="10003" >Not working 1 </button>

<button type="button" ng-click="variable2()" tabindex="10003" >Not working 2 </button>

<button type="button"  ng-click="variable2()" tabindex="10003" >Not working 3 </button>

<button type="button" ng-click="showname()" tabindex="10003"> working </button>
</div>

Answered By – Mihai Alexandru-Ionut

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.