Store a function as a variable in AngularJS

My goal is to dynamically call a function based on a variable that holds the function name. For instance:

var fun =function1(1,2)

Then later, fun could be assigned another function:

fun= function2(2,3)

This is just an example to illustrate my situation.

Now, I need to be able to call this function from my HTML:

HTML:

<button ng-click="{{fun}}>call</button>

The variable fun may contain either function1 or function2 at different times.

Answer №1

Because of JavaScript's first-class functions, we have the ability to pass them around just like any other variable.

Take a look at this JSFiddle demonstration where clicking on Change Handler switches between f1 and f2.

HTML

<body ng-app="exampleApp" ng-controller="appCtrl">
    <div>
        <h3>{{name}}</h3>
        <br>
        <button type="button" class="btn btn-primary" ng-click="fun()">Show Name</button>
        <button type="button" class="btn btn-primary" ng-click="changeClick()">
          Change Handler
        </button>
        <br>
        <h3 ng-show="clicked">You did it {{name}}</h3>
    </div>
</body>

JavaScript

var app = angular.module('exampleApp', []);

app.controller('appCtrl', function($scope){

    function f1() {
        $scope.name = "Chris";
    }

    function f2() {
        $scope.name = "Harry";
    }

    $scope.fun = f1;

    $scope.changeClick = function() {
      if($scope.fun === f1) {
        $scope.fun = f2;
      } else {
        $scope.fun = f1;
      }
    };

    $scope.name = "Default";
});

The snippet demonstrates how changeClick flips the value of fun

Answer №2

Avoid using {{}} when trying to access a variable, simply refer to the variable name directly.

function bar() {
    console.log("running bar");
}

$scope.run = bar;

<button ng-click="run()">execute</button>

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

The printing function for the window system can cause disruptions to the layout of the table

After creating a page with a simple table that can be filled in and printed, I noticed some issues with the table formatting after printing. The intended table design was supposed to look like this: https://i.stack.imgur.com/aAk89.png However, upon print ...

Do I need to define dependencies within the package.json file?

Until recently, I hadn't even heard of the package.json file. Despite this, all of my small projects have run smoothly without it. When installing npm modules globally, I typically use var x = require("express");"just for example" ...

Vue alert: The element <testimonial-photo-inner> cannot be located

After adding VueJS to my website, I am encountering numerous console errors similar to the one above. Although I have not yet attempted to create any Vue components, there are several custom HTML tags present on my site. Does VueJS automatically interpret ...

Executing multiple AngularJS HTTP POST requests in a loop and utilizing the response from each call

I am currently working with an array in my application, where I need to create data using HTTP POST calls. Each call returns an ID which is needed as input for the next call. Here is a snippet of the code: The goal is to establish a hierarchy where &apos ...

Using inline styles can cause Content Security Policy (CSP) violations in applications

I have been diligently working on an application for quite some time using create-react-app. Recently, I decided to update to the latest version of React only to find out that a new Content Security Policy (CSP) has been implemented. To my dismay, upon tr ...

Redux Form: Input remains untouched with `touched: false'

Looking to validate my input fields and dynamically change the CSS based on user interaction. To start, I implemented a required validation method by wrapping all input components with a <Field> tag and passing an array of functions to the validate ...

Having trouble transforming my JSON file into a JavaScript object

I have a JSON file with the following structure: { "branding": { "body": { "header_text_color": "#224466", "body_text_color": "##224466", "background_color": &quo ...

Transitioning from AngularJS version 1.5.0 to 1.5.8

My bower.json file contains various dependencies, including AngularJS at version 1.5.0. I am looking to update AngularJS to version 1.5.8 without causing issues for my team members. I attempted to use bower install angular#1.5.8 --save, but this resulted ...

How can I retrieve console log information in POSTMAN when a test fails?

Having an issue with this test. I am trying to trigger a console.log when the installment value in my JSON is less than 100 (resulting in a test FAIL). However, I am receiving both PASS and FAIL results in the test, but no information is showing up in th ...

PHP form headaches: issues with submitting and posting

I'm having trouble with the submit button in my PHP code. Here's what I have so far (it's for a website where users can rate things): <form method="POST> <input type="radio" name="person" value="1" /> <input type="radio" name ...

What is the correct way to send an HTTP error code to an error handling middleware?

Currently, I am in the process of developing a RESTful API using node.js and express framework. I would like to create a single error handling middleware for this project. The approach I am currently considering involves: router.get('/some-resource&a ...

Nuxt js - Components are replicated on SSR pages

I have created a static page containing various components. When I navigate to this page from another page, everything displays correctly. However, when I directly land on the page, some components are duplicated and rendered again after the footer. Upon i ...

What is the best folder structure guideline for storing custom typings in a Vue project that utilizes TypeScript?

Where is the best place to store your custom type definition files in a Vue project? I typically use a directory called ./src/types along with this type of tsconfig: { "compilerOptions": { ... "typeRoots": [ "node_modules/@types", " ...

Tips for saving two text inputs using a JavaScript function into a single .txt file

Currently, I'm developing a webpage where users can input values into two textarea fields. Upon clicking the submit button, the program should trigger a download of both text inputs and store them in a text file. While I have successfully managed to s ...

Accessing the parent scope from a directive within a nested ng-repeat in AngularJs

Seeking guidance on accessing the parent scope within a directive nested in an ng-repeat. Here is an example: <div ng-app="myApp" ng-controller="myCtrl"> <div ng-repeat="section in sections"> {{section.Name}} <div ng-rep ...

Inject a combination of HTML and JavaScript code into the Selenium Webdriver

I am facing a challenge where I have an HTML document stored in memory as a string, and it includes a <script> tag with a script that manipulates the DOM. My goal is to load this HTML page into Selenium WebDriver and retrieve the modified version aft ...

Struggling to properly test the functionality of my NgForm call in Angular2+

I've been trying to test the login functionality by inputting username and password in an NgForm, but I keep encountering unsuccessful attempts. Is there a vital step that I may be overlooking? Currently, I'm facing this error message: Chrome 6 ...

After enabling by javascript and postback, the selected item in the ListBox is not displaying correctly

I encountered a strange issue with a JavaScript function I have to enable a listbox that is disabled when it loads. The function works perfectly to enable or disable the listbox. However, after the user clicks the save button, it does not capture the newly ...

When using NodeJS, it is important to add a delay after establishing the connection before invoking client.emit('message') to ensure that it is properly

My Node application utilizes socket.io. Below is an excerpt from my code: io.sockets.on('connection', socket => { setTimeout(function () { console.log('a client connected!') clients.forEach(s => s.emit(' ...

Implementing interactive functionality to expanding lists in Vuetify.js

Can someone help me figure out how to add an active state for lists in Vuetify? I want the lists to have a primary background color, just like they show in their documentation: This is my code: <template> <v-navigation-drawer width="300px& ...