Is it possible to dynamically call a function with the function name string coming from a database, such as "myNameIsGopal"?
Currently, I am able to call a function using window["myNameIsGopal"], even if it is not in the controller. However, I would like to be able to call a function inside an Angular controller dynamically.
Here is the function defined outside the controller that I can call using window["myNameIsGopal"]:
function myNameIsGopal(args){
alert(args);}
But ideally, I want to be able to call a method like this from within the controller:
$scope.myNameIsGopal = function(args) {
alert(args);
};
Below is an example of my HTML page:
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abccc3cad8c1ccd38fcbc2e291dec3dec8">[email protected]</a>" src="https://code.angularjs.org/1.3.16/angular.js" data-semver="1.3.16"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<input type="text" ng-model="value" ng-enter="hideToolTip(event)" />
<input type="button" ng-model="gobar" ng-click="dynamicCaller('myNameIsGopal','banana')" value="click me">
And here is the code from App.js:
var app = angular.module('plunker', []);
function myNameIsGopal(arg){
alert(arg);
}
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.dynamicCaller = function(arg1, arg2) {
window[arg1](arg2);
}
$scope.myNameIsGopal = function(arg) {
alert(arg);
}
$scope.hideToolTip = function(event) {
alert(event);
}
});