简体   繁体   中英

Dynamically change button name to execute other function in angular js

I want to change a button name once it is clicked.There are two function differently Add and Subtract. first time button name is 'Add',when it clicked it should execute add number function and then name dynamically change button name to Subtract and once i clicked to subtract it should execute subtract function and again name of button come to Add which is previous. How can I do this? how to call a different function like add function when button toggle is add and vice versa.

Try the following

Controller

export class AppComponent {
  buttonNameToggle = true;
  buttonName: 'Add' | 'Subtract' = 'Add';

  onMouseUp() {
    this.buttonName = this.buttonNameToggle ? 'Add' : 'Subtract';
  }
}

Template

<button (mouseup)="buttonNameToggle = !buttonNameToggle; onMouseUp()">{{ buttonName }}</button>

Update: AngularJS

Controller

var module = angular.module("myModule", []);
module.controller("myController", function($scope) {
  $scope.toggle = true;
});

Template

<div ng-app="myModule">
  <div ng-controller="myController">
    <button ng-click="toggle = !toggle">
      {{ toggle ? 'Add' : 'Subtract' }}
    </button>
  </div>
</div>

Working example: JSFiddle

Update: call different event handlers

Controller

var module = angular.module("myModule", []);
module.controller("myController", function($scope) {
  $scope.toggle = true;
  
  $scope.add = () => { console.log('add called') };
  $scope.subtract = () => { console.log('subtract called') };
});

Template

<div ng-app="myModule">
  <div ng-controller="myController">
    <button ng-click="toggle = !toggle; toggle ? subtract() : add()">
      {{ toggle ? 'Add' : 'Subtract' }}
    </button>
  </div>
</div>

Add the event handlers based on the status of the toggle variable. If toggle is true call subtract() , if not call add() function.

Working example: JSFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM