Switch between two functions by clicking a button

Presented here is a button that serves as a toggle switch:

<button ng-click="togglefunction()">Toggle Data</button>

Below is the toggle functionality:

 $scope.toggleToolPanel = function () {
        // The goal is to include the following 2 functions so that on the first click, function1 executes, and on subsequent clicks, function2 executes.
    };

These are the two functions that will run alternatively within the toggleFunction:

 function function1(params) { 
                return '<span  >' + data + '</span>';
    }

function function2(params) { 
                return '<span  >' + data *100 + '</span>';
    }

Answer №1

Make sure to include the code snippet below in your controller:

$scope.isFirstFunction = false;

Then update your toggleToolPanel function as shown here:

$scope.toggleToolPanel = function() {
    $scope.isFirstFunction = !$scope.isFirstFunction;
    if($scope.isFirstFunction) {
        executeFunction1(params);
    } else {
        executeFunction2(params);
    }
};

Answer №2

Make sure to toggle a specific class on the button when it is clicked by utilizing classList.toggle. Upon clicking, check if the specified class is present using classList.contains. If it is present, perform action x; if not, carry out action y.

Answer №3

Check out the improved code snippet below:

const app = angular.module('mainModule', [])
         .controller('MainCtrl', ['$scope', function($scope) {
           $scope.toggle = function() {
        $scope.isToggled = !$scope.isToggled;
        var params = $scope.isToggled;

                $scope.isToggled ? toggleIn(params) : toggleOut(params);

           };

           function toggleIn(params) {
        console.log(params);
       }

           function toggleOut(params) {
        console.log(params);
           }


         }]);

<body ng-app="mainModule">
<div ng-controller="MainCtrl">
  <input type="button" value="Toggle" ng-click="toggle()" />
</div>

</body>

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 reason behind $validators not updating the $errors value in ngMessages?

When the validator is called, it returns true/false as expected. However, even when the validator returns false, the html displays the class "ng-valid" instead of "ng-invalid" as needed for ng-messages to function correctly. Using the standard "required" e ...

Reduce the amount of times append is used in JQuery

Whenever I click the button in Jquery, I aim to limit the number of appends that occur. function standardRoom() { var counter = 0; if ($('select#selectBoxStandard option').length > 1) { counter++; $('#selectBoxStandard&ap ...

npm encountered an error or issue during the installation process

I have configured my proxy settings in the .npmrc file, but I am encountering errors when running the npm install command: $ npm install npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Program File ...

What is the best way to remove individual watches as I continuously trigger an event on a specific element multiple times?

Is it possible to remove watches one by one that are applied to an input field after firing them multiple times by clicking on a "start watch" button? (function(angular) { 'use strict'; angular.module('docsBindExample', []) . ...

What is the best method for transmitting additional information to an API?

Hey everyone, I'm currently struggling to send the shipping address to api/checkout. I attempted to send the body as an object with the cart details and shipping address as object properties, but that approach didn't yield any results. Is there a ...

Exploring ways to replicate the functionality of Gmail's Contact manager

Looking to develop a contact manager similar to Gmail's interface. While I have a basic understanding of AJAX and some experience with jQuery, my JavaScript skills are limited. Any suggestions for books or blogs to improve them would be welcome. Tha ...

Obtaining a Variable Element through Selector

When working with Puppeteer, I am faced with the challenge of clicking on a web button that has a dynamic id like: #product-6852370-Size. Typically, I would use the following code: page.click('#product-6852370-Size'); However, the number withi ...

Mastering form reset functionality using jquery

When attempting to register, an error is generated if any field is left blank in the form (from PHP). The input fields that have been filled out are retained using Smarty: {if isset($smarty.post.registratie.naam)} value="{$smarty.post.registratie.naam}"{el ...

Choose JSON information and modify it utilizing NODE.js with identical data

Feeling stuck.. I have a JSON file with some data and I need to manipulate it. Take a look at my JSON structure: [{ "method": "GET", "path": "/", "aliases": "", "name": "rootPath", "handler": "generatedApps/avion01/actions.HomeHandler" }, { "method": "GET ...

Comparing Mongoose and MongoDB in Node.js: Weighing the Benefits of Each

Just starting out with Node.js and noticing the multitude of libraries available to work with MongoDB. The two most popular options appear to be mongoose and mongodb. Can someone provide a comparison of the pros and cons of these extensions? Are there any ...

Various JSON Tag values occurring more than once

Upon receiving a JSON Object in HTML, I am passing it to a JavaScript function defined below. The issue arises when the same folderName appears repeatedly on the HTML page. JSON Object: { "folderName": "arjunram-test", "objects": [ { ...

Uncovering the secrets of locating and deleting arrays with the power of jQuery

Is there a way to extract data from an array list and then have it automatically removed once displayed? let fruits = ["Banana", "Orange", "Watermelon"]; For instance, if I want to select the Watermelon element from the array. After retrieving and display ...

Differentiating the angular distinction between setting a variable with ng-click and invoking a function

I've encountered a situation like this before. Let's assume the controller has these variables: $scope.valueArr = ['Hello', 'No', 'Yes']; $scope.myValue = 'Hello'; And there is an ng-repeat as follows: ...

Unusual marking on the navigation bar

Currently, I am making updates to a website that was created by a previous employee long before I joined the team. One of the requested changes is to eliminate the orange box surrounding the navigation links. The navigation appears to be generated using Ja ...

Attempting to generate a jwt results in an undefined value

Currently in the process of mastering Node.js and I am in the midst of transitioning my existing API from Python to Node. My main challenge lies in the creation of a jwt token for authentication purposes with a third-party API. However, it seems I'm e ...

Struggling to utilize the filter technique in JavaScript?

Hey there, I'm facing a challenge in my JavaScript course. The exercise requires the creation of a function that filters an array to only keep strings with less than 10 characters. I've made several attempts at solving this problem, but haven&ap ...

Experiencing Strange Issues with Jquery Image Carousel... Assistance Needed!

I recently created a jquery slideshow using a tutorial I found at this link: While the slideshow is functioning correctly for the most part, there is a strange issue that occurs right at the beginning when displaying the first image. Initially, the first ...

What is the process of implementing FFT in node.js?

Struggling with implementing FFT in node.js is proving to be quite challenging for me at the moment. Despite experimenting with three different libraries, I find them all poorly documented, which only adds to the complexity of the task. My current setup i ...

Obtaining a result from a Promise in AngularJS

Here is a snippet of an Angular JS Service that I have: 'use strict'; app.factory('loggedService', ['$http', 'authService', 'customerService', function ($http, authService, customerService) { var out = ...

An effective method for retrieving textarea data in Node.js

I am facing an issue where I cannot successfully send data from a <textarea> to Node.js. It seems that the data I'm trying to send is not being received by Node.js. To retrieve data in Node.js: continueBtn.addEventListener("click", ...