Reputation: 31
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.
Upvotes: 0
Views: 2278
Reputation: 31125
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>
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
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
Upvotes: 1