0

I want to call a function dynamically as the function name string will come from database. ie "myNameIsGopal".

Using window"myNameIsGopal", I am able to call a function which is not there in the controller, but I want to call a function inside angular controller dynamically.

Right now, I have defined following function outside the controller, which I am able to call using window"myNameIsGopal"

function myNameIsGopal(args){
alert(args);}

But I want to call a method like this from inside of the controller.

$scope.myNameIsGopal=function(args){
alert(args);
};

Below is 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="[email protected]" 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">`enter code here`
  </body>

</html>

Below is App.js code:

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

1 Answer 1

5

You were close, as function are defined in $scope object use it not window

$scope.dynamicCaller=function(arg1,arg2){
   $scope[arg1](arg2);
}

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.dynamicCaller = function(arg1, arg2) {
    $scope[arg1](arg2);
  }
  $scope.myNameIsGopal = function(arg) {
    console.log(arg);
  }
  $scope.hideToolTip = function(event) {
    console.log(event);
  }
});
<script src="https://code.angularjs.org/1.3.16/angular.js"></script>
<div ng-app="plunker" ng-controller="MainCtrl">
  <p>Hello {{name}}!</p>

  <input type="button" ng-click="dynamicCaller('hideToolTip', 'mango')" value="click hideToolTip"/>

  <input type="button" ng-click="dynamicCaller('myNameIsGopal','banana')" value="click myNameIsGopal">
</div>

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

1 Comment

Thanks a lot paji.

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.