Ways to trigger an AngularJS function dynamically when clicking on `ng-click`?

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

Answer №1

Almost there! Remember, functions are defined in the $scope object, not in the 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with incorrect date being retrieved in MongoDB response from a node server

My date in mongodb is structured as follows: ISODate("2020-08-03T00:00:00.000+05:30"), However, after querying the date, it appears like this: 2020-08-02T18:30:00.000Z I am looking to get the correct date of 2020-08-03. What could I be doing wr ...

Stop the bubbling effect of :hover

How can the hover effect be prevented for the parent element when hovering over its children? Please take a look at the following code snippet: const parent = document.getElementById('parent') parent.onmouseover = function testAlert(e) { /* ...

Leverage Vue's ability to inject content from one component to another is a

I am currently customizing my admin dashboard (Core-UI) to suit my specific needs. Within this customization, I have an "aside" component where I aim to load MonitorAside.vue whenever the page switches to the Monitor section (done using vue-router). Here ...

The JavaScript in the Laravel file isn't functioning properly, but it works perfectly when incorporated via CDN

Successfully implemented code: <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script> <script type="text/javascript"> var textWrapper = document.querySelector('.ml6 .letters'); textWrapper.in ...

In search of an improved scoring system for matching text with JavaScript

For many of my projects, I've relied on String Score to assist with sorting various lists such as names and countries. Currently, I am tackling a project where I need to match a term within a larger body of text, like an entire paragraph. Consider t ...

Obtain document via Angular 2

Is it possible to use TypeScript to download an image that is already loaded? <div *ngIf="DisplayAttachmentImage" class="fixed-window-wrapper_dark"> <button class="btn btn-close-window" (wslClick)="HideAttachmentImage()"> & ...

I encountered an issue while trying to build a website using React-static: the module 'perf_hooks' could not be found

Encountered an issue while trying to create a site with the react-static create command: Error: Cannot find module 'perf_hooks' at Function.Module._resolveFilename (module.js:469:15) at Function.Module._load (module.js:417:25) at Mod ...

webpack is failing to load SVG files

My application structure includes: /webapp /lib /assets ic_add_black_24px.svg ic_clear_black_24px.svg .. .. The configuration in my webpack.config.js looks like this: var path = require('path'), webpack = requ ...

Incorporating text box input into a data table

When I click the "add game" button, I want the value of the input named "game-name" to appear in the "Name of the game" column of a table. Additionally, I am experiencing issues with the delete button functionality. Below is the code snippet I am working ...

AngularJS relies heavily on the concept of internationalization, commonly referred

I18n key: "step1.download":"{{n0}} Get {{n1}} More content." Within my website: <span translate=step1.download translate-values="{ n0: '{{info0}}', n1: '{{info1}}'}"></span> Within my application logic: $scope.download ...

Grid layout showcasing masonry gallery

I've spent some time looking for a Masonry gallery with a grid layout, but couldn't find one that suited my needs. So, I decided to create my own. I implemented a customElement with grid layout, but encountered an issue when trying to assign grid ...

Diving into Angular2 template forms: unraveling the mysteries of the reset function

After going through the template forms tutorial in Angular2, I'm facing a bit of confusion regarding the behavior of the native reset JavaScript function on Angular2 ngModel. While it's not explicitly clarified in the official documentation, my u ...

The state variables of React components do not always retain their most recent value

Currently, I am working on implementing the functionality of an event based library called powerbi-client-react. The first step involves retrieving the component using getEmbeddedComponent and storing it in the variable report. Then, I need to utilize the ...

Starting objects before utilizing them in the useFrame() function in react-three-fiber

I am currently working on a project using react-three-fiber to create a scene. However, I am facing an issue with placing 3D objects at different random positions. I tried using a for loop inside useFrame to set random positions, but this causes the partic ...

Is there a way to make all cards in material ui the same height?

My challenge lies in rendering cards in a grid list using material-ui. Each card comprises an image file at the top and some content in the rest of the space. However, variations in text content cause differences in card height. Despite several attempts, I ...

Tips for customizing the toggle animation styling

I'm new to HTML and CSS, currently working on designing a website for our conference. I've implemented a toggle effect for displaying the information about invited speakers along with their research interests using the following code: <!DOCTY ...

What is the duration of time that broadcast has been in existence?

I have a button on my page. When a user clicks the button, it triggers the following code: as.controller('CustSummary', function($scope, $rootScope, $http, $routeParams, $location) { var loadAbbDetails = function() { ...

Using MeanJS to assign a Mongoose object reference to an array in Angular

Having an issue with MeanJS and using the $update function of the $resource service in Angular provided by MeanJS. Here is a basic outline of my problem: Mongoose schema: var mongoose = require('mongoose'), Schema = mongoose.Schema; var Lotion ...

What is the reason for encountering an error when using the ForwardRef with a pair tag

I am facing an issue with my React app that has 3 tsx (jsx) files: First, in my index.tsx file: import ReactDOM from 'react-dom'; import Page from './Page'; ReactDOM.render( <Page /> ...

Updating an HTML value based on the selected option using JavaScript

I'm working on a form that included a select element: <select class="form-control"> <option>10 pc</option><!--1 USD --> <option>20 pc</option><!--2 USD --> <option>50 pc</option><!--3 USD ...