Executing a function in AngularJS by dynamically constructing its name as a string

Currently, I am faced with a scenario where the main functions are named as:

Add_<Element_Type>_Page()

The parameter Element_Type is passed to these functions.

I have identified two potential methods to handle calling the correct function:

  1. Create an extensive switch statement that covers all possible values of Element_Type, or

  2. Utilize an existing technique or method (that I may not be aware of) to generate a string based on the received Element_Type and call a function whose name matches that string.

All functions that can be called in this manner share identical parameter signatures.

Clearly, Option 2 seems more favorable (simpler to maintain and versatile since no modifications are required when introducing new page types).

Can this be implemented within the AngularJS framework?

Thank you in advance.

Answer №1

To achieve this, simply utilize the [...] notation in place of .

For example,

$scope["Add_" + Element_Type + "_Page"]()

will result in calling $scope.Add_test_Page() assuming Element_Type is set to test

or if you are using the controllerAs syntax,

vm["Add_" + Element_Type + "_Page"]()

where Element_Type is a parameter that has been passed as mentioned.

If you wish to use this within HTML, ensure that you have a reference to your Element_Type in either $scope or vm (depending on your approach) for access.

Answer №2

Define an attribute called "func-name" and assign your dynamic string value, representing the function name, to that attribute. You can then utilize this within your directive in the following manner:

scope: {
 funcName: '@'
},
controller: function() {
 $scope[$scope.funcName]();
}

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

What is the best way to programmatically download a file in Angular 4 without explicitly specifying the file name?

Below is the code snippet: importedSaveAs(blob, 'somefile.txt'); I'm currently facing an issue with hard-coding the file name in the above code. I would like to make it dynamic based on the response header. However, I'm unable to acc ...

Utilizing variable values in Google Charts with AngularJS

Hello everyone, I am attempting to display a chart using data obtained from an API. The output of the API is in the form of List<String> and not in JSON format. Here is the snippet of my JS file: google.load('visualization', '1', ...

Refresh the dropdown menu options using Dojo's AJAX capabilities

Hi there, I'm currently using the code below to create a cascading dropdown menu. In this code, I have a function called xyz() which makes an AJAX call to a servlet and sets the result in a variable separated by commas. Then, I split the result by com ...

Utilizing Angular.js to efficiently decode JSON files

I'm trying to extract the bitcoin price from a json file using angular.js. The json data is available through this blockchain api. Here is the angular.js code snippet I am using: <div ng-app="myApp" ng-controller="customersCtrl"> <ul> ...

Using Query strings in JavaScript: A Quick Guide

I recently completed a calculator project with only two pages. However, I am struggling to figure out how to pass input field values from one page to another. Despite trying multiple methods, nothing seems to be working. Does anyone know how to successful ...

Tasks should be defined prior to being referenced in order to avoid any issues

Utilizing multiple files with gulp@4, the main gulpfile.js includes all other files within the ./tasks/ directory. We have implemented the npm gulp-hub package to incorporate multiple gulpfiles within the ./tasks/ directory. However, upon calling the tasks ...

Uncovering the main document and all predecessor records in MongoDB

I am in the process of creating a publication that will provide me with a series of documents from the collection. The relationship between these documents can be seen below: { "_id" : "peRuJcPMDzZgTvWSX", "author" : "author", "type" : "art ...

My desire is for every circle to shift consecutively at various intervals using Javascript

I'm looking to draw circles in a sequential manner. I am trying to create an aimbooster game similar to . Instead of drawing all the circles at once, I want each circle to appear after a few seconds. The circles I've created currently do not g ...

Tips for utilizing Selenium to acquire links from a webpage

Is it possible to retrieve the link location of a web element in Selenium? While we can easily obtain the text from a web element and use getAttribute("href") method to get the location of a hyperlink, my need is to extract all the links present. For insta ...

Can an inline try be implemented without including a catch block as demonstrated?

I have a scenario where I need to execute code that may result in an error without catching it. If the response is not valid JSON, then the desired outcome should be 0: Here is the code snippet I am considering: var overallProgress = try {JSON.parse(text ...

Tips for concurrently executing multiple requests using axios without waiting for each request to finish

I am looking to send multiple requests using Axios simultaneously, without waiting for each request to finish sequentially. What I aim to achieve is to have the second request process and return even while the first request is still pending. I do not want ...

JavaScript's inability to load images lazily poses a significant challenge

I'm having trouble implementing lazy loading for my images using JavaScript. When I change the html attribute from src to data-src, the images do not display at all. Additionally, when attempting to use an intersectionObserver to lazily load the image ...

The display of Bootstrap Cards may become distorted when incorporating J Query

I am attempting to design a dynamic HTML page that pulls data from a JSON response using an AJAX request. My goal is to display three columns in a row, but currently I am only seeing one column per row. I would greatly appreciate any guidance on what migh ...

Converting objects to arrays in reactJS

Here is the object structure I currently have: { DepositAmt_0: 133 DepositAmt_1: 455 DepositAmt_2: 123 DepositNotes_0: "some notes " DepositNotes_1: "some comment" DepositNotes_2: "some comme ...

The variable 'X' in Node.js is not been declared

I've been struggling with this problem, trying to fetch my most recent tweets as an array using the npm module https://github.com/noffle/latest-tweets. However, no matter how I approach it, I always encounter errors such as 'posts is not defined& ...

To close the Muix DateTimePicker, simply hit the Escape key or click anywhere outside of the picker

I'd like the DateTimePicker to only close when the user presses the action buttons, not when they click outside or press Escape. Unfortunately, I haven't found any props to control this behavior yet. <DesktopDatePicker closeOnSelect={false} s ...

It seems like I'm having trouble sharing a collection of objects

Hey there, here's where I currently stand. I've got some code that sends an array of items to a .NET WebAPI (c#). var stuff = []; $('#items').find('input').each(function(){ var text = $(this).val(); stuff.push({ ID: ...

Tips for identifying which field has been altered when utilizing Angular SchemaForm

Is there a way to determine which field has been modified when utilizing Angular SchemaForm? I have not been able to find any property that indicates this in the debugger. Appreciate your help. ...

What is the process for loading fonts in advance?

On my website's index.html I've included the following code: <link rel="preload" href="assets/fonts/Raleway-Black.ttf" as="font" type="font/ttf" crossorigin> <link rel="preload" href="assets/fonts/Raleway-Bold.ttf" as="font" type="font/ ...

Adjust the default value of the ng-model for an input field with a date picker

One of my inputs has a datepicker attached to it. <input id="start-date" style="width: 230px;" close-text="Close" type="text" ng-model="startDate" datepicker-popup="dd-MM-yyyy" ng-required="true"/></div> When the input is displayed, I nee ...